Avoid updates on unmounted React components

Ceci García García
Trabe
Published in
2 min readJan 2, 2018

If you’re a React developer, this warning may sound familiar to you:

Warning: setState(…): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component.

Calling setState() in an unmounted component means that the component wasn’t properly cleaned up before being unmounted, that is, your app still has a reference to an unmounted component.

How is this possible?

The common example is a component that uses promises to fetch some data and gets unmounted before promise callbacks were called:

The easiest way to avoid the warning would be by forcing the component to check its isMounted state before calling setState(). This really isn’t a solution for the problem since the callback is executed anyway causing unwanted side effects; it only removes the warning.

The idea to pursue is so, preventing promise callbacks from being executed at all in case the component had been unmounted.

Jim Sproch wrote about the “isMounted antipattern” and suggested a workaround based on “cancelable promises”. With this approach, not only is the warning avoided but the callback is prevented from being executed.

Cancelable promises

cancelablePromise was originally defined by @istarkov as:

Solution

To implement the solution in your component, you only have to wrap every promise within the cancelablePromise and cancel them just before the component gets unmounted, that is, in componentWillUnmount:

Wrapping Up

Making your promises cancelable allows you to ensure that callbacks will only be executed if the context is still appropriate for it.

--

--