Cancel All Subscriptions and Asyncs in the componentWillUnmount Method, how?

前端 未结 3 1497
鱼传尺愫
鱼传尺愫 2020-12-09 14:58

I\'m getting an error message due to an async method issue. In my terminal I\'m seeing:

Warning: Can\'t call setState (or forceUpdate) on an unmounted compon         


        
3条回答
  •  旧巷少年郎
    2020-12-09 15:40

    You can use isMounted React pattern to avoid memory leaks here.

    In your constructor:

    constructor(props) {
        super(props);
    
        this._isMounted = false;
    // rest of your code
    }
    
    componentDidMount() {
        this._isMounted = true;
        this._isMounted && this.getImage(this.props.item.image);
    

    }

    in your componentWillUnmount

    componentWillUnmount() {
       this._isMounted = false;
    }
    

    While in you 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
        })
    }
    

    A recommend approach to use Axios which is based cancellable promise pattern. So you can cancel any network call while unmounting the component with it's cancelToken subscription. Here is resource for Axios Cancellation

提交回复
热议问题