-
Notifications
You must be signed in to change notification settings - Fork 176
/
S6789.html
47 lines (46 loc) · 1.8 KB
/
S6789.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<h2>Why is this an issue?</h2>
<p>React <code>isMounted()</code> is primarily used to avoid calling <code>setState()</code> after a component has unmounted, because calling
<code>setState()</code> after a component has unmounted will emit a warning. Checking <code>isMounted()</code> before calling <code>setState()</code>
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.</p>
<p>When using ES6 classes, using <code>isMounted()</code> is already prohibited.</p>
<pre data-diff-id="1" data-diff-type="noncompliant">
class MyComponent extends React.Component {
componentDidMount() {
mydatastore.subscribe(this);
}
dataHandler: function() {
if (this.isMounted()) { // Noncompliant: isMounted() hides the error
//...
}
}
render: function() {
//... calls dataHandler()
}
});
</pre>
<p>Find places where <code>setState()</code> 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
<code>componentWillUnmount</code>, before the component unmounts.</p>
<pre data-diff-id="1" data-diff-type="compliant">
class MyComponent extends React.Component {
componentDidMount() {
mydatastore.subscribe(this);
}
dataHandler: function() {
//...
}
render() {
//...
}
componentWillUnmount() {
mydatastore.unsubscribe(this);
}
}
</pre>
<h2>Resources</h2>
<h3>Documentation</h3>
<ul>
<li> React Documentation - <a href="https://legacy.reactjs.org/blog/2015/12/16/ismounted-antipattern.html"><code>isMounted</code> is an
Antipattern</a> </li>
</ul>