React Hook useEffect 缺少依赖项:'data'。要么包含它,要么移除依赖数组。
React Hook useEffect has a missing dependency: 'data'. Either include it or remove the dependency array.
ID: react/missing-dependency-array-useEffect
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| React 16.8+ | active | — | — | — |
| React 17.x | active | — | — | — |
| React 18.x | active | — | — | — |
| ESLint plugin react-hooks v4.x | active | — | — | — |
根因分析
useEffect 回调引用了变量(例如 'data'),但该变量未列在其依赖数组中,导致闭包过时或更新缺失。
English
The useEffect callback references a variable (e.g., 'data') that is not listed in its dependency array, causing stale closures or missing updates.
官方文档
https://react.dev/reference/react/useEffect#specifying-reactive-dependencies解决方案
-
将缺少的变量添加到依赖数组中。示例:useEffect(() => { console.log(data); }, [data]); -
如果变量是函数或对象,不应触发重新运行,请将其包装在 useCallback 或 useMemo 中,并包含稳定引用。示例:const stableFn = useCallback(() => { ... }, []); useEffect(() => { stableFn(); }, [stableFn]); -
如果 effect 应仅运行一次(挂载时),确保它不引用任何外部变量,或使用 refs 访问当前值而不重新运行。示例:const dataRef = useRef(data); dataRef.current = data; useEffect(() => { console.log(dataRef.current); }, []);
无效尝试
常见但无效的做法:
-
Adding // eslint-disable-next-line react-hooks/exhaustive-deps to suppress the warning without fixing the dependency.
80% 失败
Suppressing the warning can lead to stale data in effects, causing bugs that are hard to trace, especially in complex state logic.
-
Removing the dependency array entirely (useEffect(() => { ... })) to run the effect on every render.
70% 失败
This can cause performance issues and infinite loops if the effect triggers state updates, and it may not be the intended behavior.
-
Moving the variable outside the component to make it a constant (if it's not meant to change).
60% 失败
If the variable is supposed to be dynamic (e.g., from props or state), moving it outside defeats the purpose and can cause incorrect behavior.