React项目SCA扫描提示lodash过期,升级后组件报错怎么办?

Dev · 伊芃 阅读 51

刚用sca扫描工具发现项目用的lodash是4.17.20,存在高危漏洞必须升级。我执行npm install lodash@latest后,页面渲染直接报错:


// 组件里这样引用的
import debounce from 'lodash/debounce';

const SearchBar = () => {
  const handleInput = debounce((e) => {
    console.log(e.target.value);
  }, 300);

  return <input onChange={handleInput} />;
};

export default SearchBar;

控制台提示”_0.default.debounce is not a function”,但文档里写升级到4.17.21应该没问题啊,我该怎么调整导入方式?

我来解答 赞 14 收藏
二维码
手机扫码查看
2 条解答
开发者文斌
懒人方案:直接改用完整包导入,别用按需加载了。这样最省事。

import _ from 'lodash';

const SearchBar = () => {
const handleInput = _.debounce((e) => {
console.log(e.target.value);
}, 300);

return ;
};

export default SearchBar;


新版lodash对按需引入支持不太好,反正我是懒得研究那些复杂的配置,这样写完事儿。
点赞
2026-03-27 18:05
书生シ美丽
问题在于lodash从4.17.21开始改成了ESM模块,你得调整导入方式。把代码改成这样就行:

import { debounce } from 'lodash';

const SearchBar = () => {
const handleInput = debounce((e) => {
console.log(e.target.value);
}, 300);

return <input onChange={handleInput} />;
};

export default SearchBar;


如果还有其他地方用到lodash,记得都改成按需引入,不然打包会出问题。我之前也被这个坑过,真是烦。
点赞 8
2026-02-18 02:00