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

其他格式: JSON · Markdown 中文 · English
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.

generic

官方文档

https://react.dev/reference/react/useEffect#cleaning-up-an-effect

解决方案

  1. 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(); }, []);`
  2. For timeouts, use clearTimeout in cleanup: `useEffect(() => { const timer = setTimeout(() => setState(...), 1000); return () => clearTimeout(timer); }, []);`
  3. Use a library like `use-http` or `react-query` that handles cancellation automatically.

无效尝试

常见但无效的做法:

  1. 90% 失败

    The async task still executes, wasting resources; React recommends cleanup instead.

  2. 95% 失败

    It can lead to memory leaks and unpredictable behavior in production, especially with frequent mount/unmount cycles.