react build_error ai_generated true

React Hook useEffect缺少依赖项:'variable'。要么包含它,要么删除依赖项数组。

React Hook useEffect has a missing dependency: 'variable'. Either include it or remove the dependency array.

ID: react/missing-exhaustive-deps

其他格式: JSON · Markdown 中文 · English
90%修复率
85%置信度
1证据数
2023-04-01首次发现

版本兼容性

版本状态引入弃用备注
eslint-plugin-react-hooks 4.6.0 active
React 18.2.0 active

根因分析

exhaustive-deps ESLint规则检测到在useEffect内部使用的变量未在其依赖项数组中列出,可能导致过时闭包或错过更新。

English

The exhaustive-deps ESLint rule detects that a variable used inside useEffect is not listed in its dependency array, potentially leading to stale closures or missed updates.

generic

官方文档

https://react.dev/reference/react/useEffect#specifying-reactive-dependencies

解决方案

  1. Add the missing variable to the dependency array. If the variable is a function, wrap it in useCallback first.
  2. If the variable is not meant to be reactive (e.g., a stable reference), use useRef to store it and access via .current.

无效尝试

常见但无效的做法:

  1. Adding // eslint-disable-next-line react-hooks/exhaustive-deps without understanding the dependency 80% 失败

    Suppressing the warning does not fix the underlying stale closure bug; it only hides the lint error.

  2. Removing the dependency array entirely ([] to undefined) 70% 失败

    Without a dependency array, the effect runs after every render, which can cause performance issues and infinite loops if it updates state.

  3. Using useRef to store the variable and reading from ref inside the effect 40% 失败

    This works but is often unnecessary and can be confusing; it also bypasses the reactive nature of the variable.