All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.l10n.javascript.rules.javascript.S6789.html Maven / Gradle / Ivy

There is a newer version: 10.17.0.28100
Show newest version

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.

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);
  }
}

Resources

Documentation





© 2015 - 2024 Weber Informatics LLC | Privacy Policy