react
runtime_error
ai_generated
true
警告:无法在已卸载的组件上执行 React 状态更新。这是一个空操作,但表明您的应用程序中存在内存泄漏。要修复,请在 useEffect 清理函数中取消所有订阅和异步任务。
Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
ID: react/setstate-on-unmounted-component-with-async
90%修复率
87%置信度
1证据数
2023-09-10首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| React 18.2.0 | active | — | — | — |
| React 19.0.0 | active | — | — | — |
| React 16.14.0 | active | — | — | — |
根因分析
异步操作(例如 fetch、timeout)在组件卸载后完成,回调尝试在已卸载的组件上设置状态。
English
An async operation (e.g., fetch, timeout) completes after the component has unmounted, and the callback attempts to set state on the unmounted component.
官方文档
https://react.dev/reference/react/useEffect#cleaning-up-an-effect解决方案
-
Use an AbortController with fetch and call abort() in the useEffect cleanup: `const controller = new AbortController(); useEffect(() => { fetch(url, { signal: controller.signal }); return () => controller.abort(); }, []);` -
For timeouts, use clearTimeout in cleanup: `useEffect(() => { const timer = setTimeout(() => setState(...), 1000); return () => clearTimeout(timer); }, []);` -
Use a library like `use-http` or `react-query` that handles cancellation automatically.
无效尝试
常见但无效的做法:
-
90% 失败
The async task still executes, wasting resources; React recommends cleanup instead.
-
95% 失败
It can lead to memory leaks and unpredictable behavior in production, especially with frequent mount/unmount cycles.