javascript - 未安装组件的状态更新如何导致内存泄漏?

标签 javascript reactjs memory-leaks

更新未安装组件的状态如何导致内存泄漏?

已知如何修复以下错误(one solutionanother solution)

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.

但是当组件刚刚被关闭并且不再需要时,用“isUnmounted”检查乱丢我的 promise 链似乎很奇怪。这是如何导致内存泄漏的?

最佳答案

How does this cause a memory leak?

不能保证,但这可能取决于导致您在卸载后设置状态的原因。例如,如果您有一个 setInterval 在卸载后继续运行,则该函数及其闭包中的任何变量都不能被垃圾回收。

class ExampleComponent extends React.Component {
  state: { seconds: 0 }
  componentDidMount() {
   setInterval(() => {
     this.setState(prev => ({
       seconds: prev.seconds + 1;
     });
   }, 1000);
  }
  // No clearing the interval in componentWillUnmount
}

在上面的代码中,set interval 中的匿名函数不能被垃圾回收,这反过来意味着 this 不能被回收,所以组件将永远卡在内存中。

关于javascript - 未安装组件的状态更新如何导致内存泄漏?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59161507/

相关文章:

javascript - Redux - 管理预加载状态

reactjs - 如何使用 Gulp 和 Babel 将 .jsx 转换为 .js?

objective-c - 返回对象上的内存泄漏

javascript - .val() 不返回输入文本

javascript - 如何按州和行/列在气泡图中定位气泡

javascript - 为什么我使用 jest-dom 时会报错 "TypeError: expect(...).not.toBeVisible is not a function"

objective-c - WebView:启用 ARC 的应用程序中的 libdispatch 泄漏

java - 清除图表会导致内存泄漏吗?

javascript - cordova 插件无法工作

javascript - sails.js 模糊错误信息。使用 xmlHttpRequest()