How does updating the state of an unmounted component cause a memory leak?
It is known how to fix the following error (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.
But it seems odd to litter my promise chains with "isUnmounted" checks when the component has just been dismissed and is not needed anymore. How does this cause a memory leak?
How does this cause a memory leak?
It's not guaranteed to, but it might depending on what's causing you to set state after unmount. For example, if you have a setInterval
that's continuing to run after unmount, that function and any variables in its closure cannot be garbage collected.
class ExampleComponent extends React.Component {
state: { seconds: 0 }
componentDidMount() {
setInterval(() => {
this.setState(prev => ({
seconds: prev.seconds + 1;
});
}, 1000);
}
// No clearing the interval in componentWillUnmount
}
In the above code, the anonymous function inside set interval cannot be garbage collected, which in turn means this
cannot be collected, so the component will have to hang out in memory forever.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With