Skip to content Skip to sidebar Skip to footer

When Use Componentdidmount() I Found This Error : Can't Call Setstate

I found this error : 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 subsc

Solution 1:

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 error message clearly states that your application has memory leak. What's going on here exactly?

Well, you're using async operation (loadEntityNameById) in setBreadcrumbs method. Which is being called in componentWillMount and in componentWillReceiveProps. This means when you go from CampaignPage component to BreadCrumb component, it will do the async operation ie. loadEntityNameById is running in the background which only sets the state once it's finished. But until that time your BreadCrumb component might be unmounted. The react application doesn't allow you to update the state on an unmounted component.

Furthermore, you should not use componentWillMount method at all. Use componentDidMount hook instead.

To fix the issue, what you can do is to set a flag like:

componentDidMount() {
  // component is mounted, set the didMount property on BreadCrumb component// you can use any name instead of didMount what you think is properthis.didMount = true// now, you can update the stateif(this.didMount) { // be sure it's not unmountedthis.setState({names: ...})
  }

Next, you should clear the didMount property when the component is unmounted.

componentWillUnmount() {
  this.didMount = false// component is unmounted

This will ensure you that your application memory will not be leaked. Because, we properly setting the state when required but not when it doesn't require, and stopping unnecessary loop.

Solution 2:

You're doing an asynchronous action (loadEntityNameById) that sets the state for the component when it finishes. By that time, your Breadcrumbs component may have been unmounted, and the error is thrown.

Solution 3:

You cannot call setState in componentWillMount try using componentDidMount instead

Post a Comment for "When Use Componentdidmount() I Found This Error : Can't Call Setstate"