Tag Archives: Can’t call setState (or forceUpdate) on an unmounted component

Can’t call setState (or forceUpdate) on an unmounted component [How to Solve]

Can’t call setState (or forceUpdate) on an unmounted 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.

can not call the setState () scheme in the component that has been destroyed. The scenario appears as follows: the jump route is destroyed, and the internal component of the component is also destroyed by the asynchronous operation, such as HTTP request, state setTimeOut, update state, state status information.

The idea is to control the asynchrony of the component before it is unloaded.
solution 1: rewrite the setstate method before the component is destroyed to make no change to the state.
componentwillunmount() {
this. Setstate = (state, callback) = & gt{
return;
};
}
solution 2: before a component is destroyed, it can be set state. After destruction, it cannot be set state
componentwillmount() {
this_ Ismounted = true
fetch (‘network request ‘). Then (status, response) = & gt{
if (this._ isMounted) {
this.setState({
activityTipsImg: response.data.tips_ url,
activityTipsContent: response.data.tips_ content
})
}
});
}
componentWillUnmount() {
this._ Ismounted = false
}