解决 React componentWillUnmount中卸载异步操作,防止内存泄漏

在React开发中,我们快速/频繁的切换两个组件,可能会遇到如下问题:
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.

大白话就是:我们不能在组件销毁后设置state!

解决办法

 function inject_unount (target){
        // 改装componentWillUnmount,销毁的时候记录一下
        let next = target.prototype.componentWillUnmount
        target.prototype.componentWillUnmount = function () {
            if (next) next.call(this, ...arguments);
            this.unmount = true
         }
         // 对setState的改装,setState查看目前是否已经销毁
        let setState = target.prototype.setState
        target.prototype.setState = function () {
            if ( this.unmount ) return ;
            setState.call(this, ...arguments)
        }
    }
    @inject_unount
    class BaseComponent extends Component {
    
    }
    //以后我们写组件时直接继承BaseComponent
PS:未来的你,一定会感谢今天拼命努力的自己!

你可能感兴趣的:(前端,常见问题与解决方案)