Skip to content

警告: 能't 执行 React 状态更新 on unmounted 组件

错误信息

                能't 执行 React 状态更新 on unmounted 组件. 这个是 否-op, 但它 indicates memory leak in 你的 application.
              

快速摘要

异步操作 (获取, setTimeout, Promise) 已完成之后组件 unmounted and tried 到 call setState, indicating memory leak.

为什么发生

  • 异步获取 or API call resolves 之后组件 unmounts

  • setInterval/setTimeout 回调 fires 之后 unmount

  • 事件监听器 wasn't 移除 on unmount

  • subscription wasn't cleaned 上 in useEffect

最小示例

✗ 错误代码
useEffect(() => {
  fetchData().then(data => setData(data)); // No cleanup!
}, []);
✓ 修复代码
useEffect(() => {
  let cancelled = false;
  fetchData().then(data => {
    if (!cancelled) setData(data);
  });
  return () => { cancelled = true; };
}, []);

cancelled flag prevents setData 从是 called 之后 unmount. cleanup 函数设置它 到真 当组件 unmounts.

如何诊断

  • Look for 异步操作 in useEffect 不使用 cleanup

  • 检查 for setInterval/setTimeout 不使用 clearInterval/clearTimeout in cleanup

  • 验证事件监听器是 移除 in useEffect cleanup 函数

如何修复

  • 添加 cleanup 函数到 useEffect 那个取消异步操作

  • Use isMounted ref 到检查之前 calling setState

  • Use AbortController 到取消获取请求 on unmount

如何预防

  • 总是返回 cleanup 函数从 useEffect 当设置 subscriptions or timers

  • Use AbortController for 获取请求

相关资源

相关术语

相关课程

  • useEffect

    学习 cleanup 函数到 prevent memory leaks.

← 返回语言