Avoid usage of deprecated method `isMounted`JS-0446
The use of isMounted
is not recommended as it has been deprecated.
** Use of isMounted()
**
The primary use case for isMounted()
is to avoid calling setState()
after a component has unmounted, because calling setState()
after a component has unmounted will emit a warning. The “setState warning” exists to help you catch bugs, because calling setState()
on an unmounted component is an indication that your app/component has somehow failed to clean up properly. Specifically, calling setState()
in an unmounted component means that your app is still holding a reference to the component after the component has been unmounted - which often indicates a memory leak!
Recommended solutions
- Easy Approach
An easy migration strategy for anyone upgrading their code to avoid isMounted()
is to track the mounted status yourself. Just set a _isMounted
property to true in componentDidMount
and set it to false
in componentWillUnmount
, and use this variable to check your component’s status.
- Optimal Solution
An optimal solution would be to find places where setState()
might be called after a component has unmounted, and fix them. Such situations most commonly occur due to callbacks, when a component is waiting for some data and gets unmounted before the data arrives. Ideally, any callbacks should be canceled in componentWillUnmount, prior to unmounting.
Bad Practice
var Hello = createReactClass({
handleClick: function() {
setTimeout(function() {
if (this.isMounted()) {
return;
}
});
},
render: function() {
return <div onClick={this.handleClick.bind(this)}>Hello</div>;
}
});
Recommended
var Hello = createReactClass({
render: function() {
return <div onClick={this.props.handleClick}>Hello</div>;
}
});