Warning: Can’t call setState (or forceUpdate) 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 the componentWillUnmount method. – ReactJs

Hi everyone,

This is just a quick post, mostly for my future reference but hopefully it will help someone else out as well. I ran into the following error when invoking a callback in a child component:

Warning: Can't call setState (or forceUpdate) 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 the componentWillUnmount method.

This is generally a result of updating the state of a child component after the parent component has hidden it.

e.g. the child component calls a prop function which hides the child component. On the line after the prop function call the child component attempts to set a state variable.

Issue

In my case, it was because I was setting the loading state of a child component to false after performing a successful fetch. Normally this would be fine however I had hidden the child component via the parent component’s prop callback after the successful response was confirmed.

  • (Child Component): Set loading state to true.
  • (Child Component): Call API
  • (Child Component): After retrieving payload, invoke parent component’s prop function and pass it the payload
  • (Parent Component): Process payload. In render, the new payload hides the child component
  • (Child Component): Attempts to set loading state to false Error: can’t change state now that the component is no longer mounted

Solution

To get around it, I had to ensure that I didn’t invoke the parent’s callback (or unload the child) until after the child’s state had been set.

  • (Child Component): Set loading state to true.
  • (Child Component): Call API
  • (Child Component): Retrieve payload, set loading state to false place state change before parent callback is invoked
  • (Child Component): Invoke parent component’s prop function and pass it the payload
  • (Parent Component): Process payload. In render, the new payload hides the child component

Now that the child component state is modified before it is unmounted there isn’t an issue. The easiest way that I’ve found to debug errors like this is to set breakpoints (either hardcoded or in the console) to ensure that everything is being invoked in the expected order.

If you need any more info please let me know!

Thanks,
Chris

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.