withUnmounted icon indicating copy to clipboard operation
withUnmounted copied to clipboard

HOC for set a flag when componentWillUnmount, bypass `Can't perform a React state update on an unmounted component` warning

withUnmounted

HOC for set a hasUnmounted flag when componentWillUnmount, bypass Can't perform a React state update on an unmounted component warning

Install

npm install --save @ishawnwang/withunmounted

Usage

import withUnmounted from '@ishawnwang/withunmounted'

class YourCompoment extends Component {
  hasUnmounted = false;

  componentDidMount() {
    fetch(url).then(resp => {
      if (this.hasUnmounted) {
        // check hasUnmounted flag
        return;
      }
      this.setState({ resp });
    });
  }
}

export default withUnmounted(YourCompoment);

Detail

Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

According to official document, it's fine to call setState in componentWillUnmount, it won't produce any unpredicable effect, just a warning should be ignore.

Additional Infos

https://reactjs.org/blog/2015/12/16/ismounted-antipattern.html