React isMounted()
is primarily used to avoid calling setState()
after a component has unmounted, because calling
setState()
after a component has unmounted will emit a warning. Checking isMounted()
before calling setState()
does eliminate the warning, but it also defeats the purpose of the warning, which is raising awareness that the app is still holding a reference to
the component after the component has been unmounted.
When using ES6 classes, using isMounted()
is already prohibited.
class MyComponent extends React.Component {
componentDidMount() {
mydatastore.subscribe(this);
}
dataHandler() {
if (this.isMounted()) { // Noncompliant: isMounted() hides the error
//...
}
}
render() {
//... calls dataHandler()
}
};
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
, before the component unmounts.
class MyComponent extends React.Component {
componentDidMount() {
mydatastore.subscribe(this);
}
dataHandler() {
//...
}
render() {
//...
}
componentWillUnmount() {
mydatastore.unsubscribe(this);
}
}