# React Hook useEffect 缺少依赖项：'data'。要么包含它，要么移除依赖数组。

- **ID:** `react/missing-dependency-array-useEffect`
- **领域:** react
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

useEffect 回调引用了变量（例如 'data'），但该变量未列在其依赖数组中，导致闭包过时或更新缺失。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| React 16.8+ | active | — | — |
| React 17.x | active | — | — |
| React 18.x | active | — | — |
| ESLint plugin react-hooks v4.x | active | — | — |

## 解决方案

1. ```
   将缺少的变量添加到依赖数组中。示例：useEffect(() => { console.log(data); }, [data]);
   ```
2. ```
   如果变量是函数或对象，不应触发重新运行，请将其包装在 useCallback 或 useMemo 中，并包含稳定引用。示例：const stableFn = useCallback(() => { ... }, []); useEffect(() => { stableFn(); }, [stableFn]);
   ```
3. ```
   如果 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.** — Suppressing the warning can lead to stale data in effects, causing bugs that are hard to trace, especially in complex state logic. (80% 失败率)
- **Removing the dependency array entirely (useEffect(() => { ... })) to run the effect on every render.** — This can cause performance issues and infinite loops if the effect triggers state updates, and it may not be the intended behavior. (70% 失败率)
- **Moving the variable outside the component to make it a constant (if it's not meant to change).** — 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. (60% 失败率)
