A bit late to this, but, I have recently started looking into the unmounted setState warnings thrown by React where they mention this could lead to memory leaks.
There is a blog post mentioning how isMounted() or having your own isMounted is an antipattern https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html
There is a twitter thread where Dan Abramov explains why this is an anti-pattern and how it can lead to memory leaks. The gist being that the promise then/catch handler would still hold a reference to the unmounted component for longer than it is required. Ideally we shouldn't have this reference once the component is unmounted
I have gone through other answers on stackoverflow related to this, where it is established why this solution with cancellable promise is semantically better than the other solutions.
The ideal implementation as suggested by Dan is to either have cancellable promises which can internally do away with those component references, or to have your own implementation of cancellable promise which might only reject the promise if it is cancelled, but should remove all references to the component.
Now, I don't really understand how this reference thing works and how this is solved by the solution suggested in the blog post (Which seems to reject the promise if it has been cancelled, but does not have a any way to remove the reference of the component)
These are the things that i want to understand:
- If in component A, in promise.then (or catch) we do not refer to
this, it would mean that the component is not referred and even if it is unmounted, it will not be a memory leak when the then handler is actually called? - If we register a
thenhandler in component A for the promise, how long does it live ? Does it ever get removed by the runtime? Would it be removed once the component is unmounted, as the component no longer keeps a reference to the promise and hence thethencallback. In this case though, thethencallback just after the component has mounted would still run as it would have been scheduled in the micro tasks queue, but this wouldn't happen anytime later ? (Which might be the reason that we only see this warning once when the component gets unmounted) - How can we manually remove the reference to a component in promise cancellation (as suggested by Dan in the twitter thread) to avoid memory leaks?
- the solution suggested in the blogpost would still lead to memory leaks? (This solution might be more semantically correct though, as compared to the isMounted solution)