48 lines
1.6 KiB
Plaintext

== Why is this an issue?
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.
[source,javascript,diff-id=1,diff-type=noncompliant]
----
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.
[source,javascript,diff-id=1,diff-type=compliant]
----
class MyComponent extends React.Component {
componentDidMount() {
mydatastore.subscribe(this);
}
dataHandler() {
//...
}
render() {
//...
}
componentWillUnmount() {
mydatastore.unsubscribe(this);
}
}
----
== Resources
=== Documentation
* React Documentation - https://legacy.reactjs.org/blog/2015/12/16/ismounted-antipattern.html[`isMounted` is an Antipattern]