取消componentWillUnmount方法中的所有订阅和异步,如何?

时间:2018-08-28 15:26:51

标签: javascript node.js reactjs react-native lifecycle

由于异步方法问题,我收到一条错误消息。在我的终端中,我看到了:

Warning: Can't call setState (or forceUpdate) 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.
- node_modules/fbjs/lib/warning.js:33:20 in printWarning
- node_modules/fbjs/lib/warning.js:57:25 in warning
- node_modules/react-native/Libraries/Renderer/ReactNativeRenderer-dev.js:12196:6 in warnAboutUpdateOnUnmounted
- node_modules/react-native/Libraries/Renderer/ReactNativeRenderer-dev.js:13273:41 in scheduleWorkImpl
- node_modules/react-native/Libraries/Renderer/ReactNativeRenderer-dev.js:6224:19 in enqueueSetState
- node_modules/react/cjs/react.development.js:242:31 in setState
* router/_components/item.js:51:16 in getImage$
- node_modules/regenerator-runtime/runtime.js:62:44 in tryCatch
- node_modules/regenerator-runtime/runtime.js:296:30 in invoke
- ... 13 more stack frames from framework internals

我注意到它特别指出了getImage$

这是我在该部分使用的代码:

export default class extends Component {
    constructor(props) {
        super(props);
        const { item } = props

        const bindThese = { item }
        this.boundActionCreators = bindActionCreators(bindThese)

        this.state = {
            image: require('../../static/logo.png'),
            ready: false,
            showOptions: this.props.showOptions
        }

        this.getImage = this.getImage.bind(this)
        this.renderNotAdmin = this.renderNotAdmin.bind(this)
        this.renderAdmin = this.renderAdmin.bind(this)
        this.handleOutOfStock = this.handleOutOfStock.bind(this)
    }

    async getImage(img) {
        let imgUri = await Amplify.Storage.get(img)
        let uri = await CacheManager.get(imgUri).getPath()

        this.setState({
            image: { uri },
            ready: true
        })
    }

    componentDidMount() {
        this.getImage(this.props.item.image)
    }

我正在尝试找出如何将此异步方法使用componentWillUnmount。我该怎么办?

谢谢!

4 个答案:

答案 0 :(得分:21)

您可以使用isMounted React模式来避免此处的内存泄漏。

在您的构造函数中:

constructor(props) {
    super(props);

    this._isMounted = false;
// rest of your code
}

componentDidMount() {
    this._isMounted = true;
    this._isMounted && this.getImage(this.props.item.image);

}

在您的componentWillUnmount

componentWillUnmount() {
   this._isMounted = false;
}

在你getImage()

async getImage(img) {
    let imgUri = await Amplify.Storage.get(img)
    let uri = await CacheManager.get(imgUri).getPath()

    this._isMounted && this.setState({
        image: { uri },
        ready: true
    })
}

一种使用 Axios 的推荐方法,该方法基于可取消的承诺模式。因此,您可以在使用cancelToken subscription卸载组件时取消任何网络呼叫。 这是Axios Cancellation

的资源

答案 1 :(得分:3)

您需要在componentWillUnmount()方法中设置this.mount = false,在componentDidMount()方法中设置this.mount = true。

setState更新是基于条件的,需要在componentDidMount()方法中声明。

componentDidMount() {
        this.mounted = true;
        var myVar =  setInterval(() => {
                let nextPercent = this.state.percentage+10;
                if (nextPercent >= 100) {
                    clearInterval(myVar);
                }
                if(this.mounted) {
                    this.setState({ percentage: nextPercent });
            }
        }, 100);
}

componentWillUnmount(){
      this.mounted = false;
}

答案 2 :(得分:2)

React blog

  

只需在componentDidMount中将_isMounted属性设置为true并将其设置   在componentWillUnmount中为false,并使用此变量检查您的   组件的状态。

接着说,理想情况下,这可以通过使用可取消的回调来解决,尽管第一种解决方案似乎在这里很合适。

您绝对不应该使用isMounted()函数,该函数可能已弃用。

答案 3 :(得分:0)

我通过覆盖 setState 方法解决了错误

<块引用>
isSubscribed = true;

componentWillUnmount() {
  this.isSubscribed = false;
}

setState = (state, callback?) => {
   if (this.isSubscribed) {
     super.setState(state, callback);
   }
}