React Hooks exhaustive-deps规则不生效,请求排查原因
排查react-hooks/exhaustive-deps规则失效问题
1. 先明确CRA的规则默认情况
CRA(react-scripts)默认内置并启用react-hooks/exhaustive-deps规则,不存在“该规则不应在CRA中运行”的说法,此信息有误。
2. 针对package.json的排查点
- 确认
eslint-plugin-react-hooks依赖存在:CRA项目默认会内置该插件,但如果手动修改过依赖,可能被误删。查看dependencies或devDependencies中是否包含该包,版本建议匹配当前react-scripts对应的版本(比如react-scripts@5.x对应eslint-plugin-react-hooks@4.x+)。 - 确认react/react-dom版本≥16.8.0:Hook及配套ESLint规则仅支持React 16.8以上版本,版本过低会导致规则无法运行。
3. 针对.eslintrc.js的排查点
- 确认插件已引入:
plugins数组中必须包含'react-hooks',否则ESLint无法识别该规则。 - 确认规则已启用:
rules对象中'react-hooks/exhaustive-deps'需设为'warn'或'error',设为'off'会直接关闭规则。 - 检查extends配置:如果继承了
'react-app'(CRA默认ESLint配置),会自动包含react-hooks规则;若自定义了extends覆盖默认配置,需确保第三方配置未禁用该规则。 - 示例正确配置片段:
module.exports = { plugins: ['react-hooks'], rules: { 'react-hooks/exhaustive-deps': 'warn', 'react-hooks/rules-of-hooks': 'error' }, extends: ['react-app'] };
4. 针对VSCode settings.json的排查点
- 确认ESLint全局启用:
"eslint.enable": true,否则编辑器不会执行ESLint检查。 - 检查是否自定义禁用规则:查看
"eslint.rules.customizations"中是否有将react-hooks/exhaustive-deps设为off的配置。 - 确认ESLint插件为最新版本:旧版本插件可能存在兼容性问题,导致规则不生效。
- 排查工作区配置:如果是工作区级别的settings.json,确认未覆盖全局ESLint设置。
5. 其他通用排查操作
- 重启VSCode:配置修改后需重启编辑器,确保ESLint加载新配置。
- 清除ESLint缓存:运行
npm run lint -- --cache或删除node_modules/.cache目录,避免缓存导致规则不生效。 - 检查代码注释:确认代码中未使用
// eslint-disable-next-line react-hooks/exhaustive-deps这类注释临时禁用规则。
内容的提问来源于stack exchange,提问作者dev_O
相关产品推荐
相关产品推荐

