批量修复 Cant't call setState(or forceUpdate) on an unmount component.方法

快速修复 Cant't call setState(or forceUpdate) on an unmount component.方法

直接原因:

在一个已经Unmounted的组件内,调用了setState方法。这个时候会导致该组件对象还存在引用,无法释放,导致内存泄漏的问题。

常见的场景:

打开某页面,在页面的DidMount方法内,发起网络请求(请求成功后,会调用setState修改页面数据),然后此时退出当前页面,页面会Unmount。此时之前发送的网络请求,返回数据,这个时候,会调用页面的setState方法。出现上述的错误。

常用处理方法:

很多文章会说可以在组件内维护一个状态值isMounted,在unmount方法内,isMounted=false,记录当前组件是否unmount。然后每次调用setState的时候,都判断一下isMounted。

评价:

该方法可以修复该问题,但是有点麻烦,没办法复用。每个页面都需要实现一遍。繁琐。

推荐做法:

使用es6的修饰器,统一处理该问题。

代码:

export function disableSetStateWhenUnmount(target) {
    if (!target || !target.prototype) {
        return;
    }
    // 重写组件的componentWillUnmount,销毁的时候记录一下
    const { componentWillUnmount, setState } = target.prototype;
    target.prototype.componentWillUnmount = function() {
        if (componentWillUnmount) {
            componentWillUnmount.apply(this, arguments);
        }
        this.willUnomunt = true; // 表示已经卸载
    };

    // 每次在执行setState之前都查看该组件是否已经销毁
    target.prototype.setState = function() {
        if (this.willUnomunt) {
            return;
        } // 已经卸载的话就不执行
        if (setState) {
            setState.apply(this, arguments);
        }
    };
}

用法:
在需要使用的组件@disableSetStateWhenUnmount就可以了

import React, { PureComponent } from 'react';
import { Text, View } from 'react-native';
import { disableSetStateWhenUnmount } from './index';

@disableSetStateWhenUnmount
export default class Example extends PureComponent {
    state = { num: 0 };

    componentDidMount() {
        this.load();
    }

    load = async () => {
        const res = await this.requestData();
        this.setState({ num: res });
    };

    requestData = () => {};

    render() {
        const { num } = this.state;
        return (
            
                 textInComponent {num} 
            
        );
    }
}

你可能感兴趣的:(批量修复 Cant't call setState(or forceUpdate) on an unmount component.方法)