更新未安装组件的状态如何导致内存泄漏?
已知如何修复以下错误(one solution、another 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/