'how to avoid the warning: Can't perform a React state update on an unmounted component
In short, the situation is that the ChildComponent may call setState() after its parent unmount it.
In my case, this ChildComponent rendered a delete-button and a delete-dialog and was rendered by Ant-Design-Table-column-render. If users click on the ChildComponent, it just shows up the delete-dialog. After confirming the deletion request, the ChildComponent will execute a callback function passed through props by its parent, and then call setState to hide the dialog. However, the parent's callback function also call the setState, which unmount ChildComponent and result in the warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application.
To avoid the warning, this isMounted is an Antipattern can be a solution. However, it also said:
Checking isMounted before calling setState() does eliminate the warning, but it also defeats the purpose of the warning`.
To improve it, is it good to wrap the setState by the below _setState? After this, the ChildComponent just call _setState instead of setState. Will the below solution avoid the memory leak, or what other problems does it have?
class ChildComponent extends React.Component {
_isMounted = false
componentDidMount () {
this._isMounted = true
}
componentWillUnmount () {
this._isMounted = false
}
_setState(newState: any) {
if (this._isMounted) {
this.setState(newState)
return
}
// component is not mounted!
Object.assign(this.state, newState)
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
