# 警告：检测到过时的闭包。传递给 useEffect 的回调引用了一个可能已过时的变量。

- **ID:** `react/stale-closure-useeffect`
- **领域:** react
- **类别:** runtime_error
- **验证级别:** ai_generated
- **修复率:** 90%

## 根因

useEffect 回调捕获了来自之前渲染的变量，当该变量发生变化时，由于依赖数组缺失或不完整，effect 仍然使用旧值。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| React 16.8.0 | active | — | — |
| React 17.0.2 | active | — | — |
| React 18.2.0 | active | — | — |

## 解决方案

1. ```
   Add all variables referenced inside the effect to the dependency array: `useEffect(() => { console.log(count); }, [count]);`
   ```
2. ```
   Use the functional update form of setState or useReducer if the stale variable is a state value: `setCount(prev => prev + 1)`
   ```
3. ```
   Use `useRef` to hold the latest value and update it via an effect: `const countRef = useRef(count); countRef.current = count;` then access `countRef.current` inside the effect.
   ```

## 无效尝试

- **** — The effect never re-runs when the captured variable changes, so the closure remains stale indefinitely. (80% 失败率)
- **** — The variable is still captured at the time of effect creation; if it changes, the effect still uses the old value. (75% 失败率)
- **** — If the ref is not manually updated when the variable changes, it still holds the old value. (60% 失败率)
