1.0.1 • Published 5 years ago

@ishawnwang/withunmounted v1.0.1

Weekly downloads
309
License
MIT
Repository
github
Last release
5 years ago

withUnmounted

npm.io npm.io npm.io npm.io

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.

npm.io

Additional Infos

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