【问题标题】:can't perform a react state update on an unmounted component. this is a no-op but it indicates a memory leak无法对未安装的组件执行反应状态更新。这是一个空操作,但它表示内存泄漏
【发布时间】:2020-09-18 16:32:47
【问题描述】:

警告:无法对未安装的组件执行 React 状态更新。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要修复,请在 componentWillUnmount 方法中取消所有订阅和异步任务。

componentDidMount() {
    this.RetrieveSellerNo();
    this.requestLocationPermission();
    this.requestData();
    this.Watch();

    this._interval = setInterval(() => {


        if (this.state.SellerNo !== null) {
            this.uploadPosition();
        }
        this.requestData();
    }, 60000);
    setTimeout(() => {
        this.requestData();
        this.StoreiposLat();
        this.StoreiposLong();
    }, 5000);
}

componentWillUnmount = () => {
    Geolocation.clearWatch(this.watchId);

}



Watch = () => {
    this.watchId = Geolocation.watchPosition(
        (position) => {
            this.setState({
                watch: {
                    lat: position.coords.latitude,
                    long: position.coords.longitude
                }
            });
        },
        (error) => {
            // console.log(error.message)
        },
        { enableHighAccuracy: false, timeout: 20000, maximumAge: 1000, } //distanceFilter:1
    );
}

【问题讨论】:

    标签: javascript react-native memory-leaks geolocation


    【解决方案1】:

    即使在卸载组件后,您的超时和/或间隔可能仍在运行并尝试更新状态。您没有清除在 componentDidMount 中创建的间隔和超时。

    像存储间隔一样存储超时。在你的 componentDidMount 中:

    this._timeout = setTimeout(...)
    

    然后,在您的 componentWillUnmount 中,执行以下操作:

    Geolocation.clearWatch(this.watchId)
    clearInterval (this._interval)
    clearTimeout(this._timeout)
    

    【讨论】:

    • 这样可以吗? setTimeout(()=>{ this.props.navigation.replace('Search'); clearTimeout(); },500) 或者我们必须在任何有 Timeout 的地方使用 componentWillUnmount ?
    • 不,这不会解决问题。超时后回调被触发,因此 clearTimeout() 没有任何效果。您应该使用 componentWillUnmount 清除卸载超时。如果您不喜欢这种方法(我也不喜欢),我建议您考虑使用 React Hooks。 Hooks 是一种编写组件的新方式,它们不使用相当丑陋的 componentDidMount、componentWillUnmount 等。
    【解决方案2】:

    我做到了。但是还是有错误。 我使用了 pureComponent 并清除了所有超时和间隔。

    我不得不说,当我从这个页面进入登录页面并返回到这个页面时,就会发生这种情况。

    每次 RAM 量增加并添加到之前的值。

    【讨论】:

    • 这样可以吗? setTimeout(()=>{ this.props.navigation.replace('Search'); clearTimeout(); },500) 或者我们必须在任何有 Timeout 的地方使用 componentWillUnmount ?
    猜你喜欢
    • 2019-12-31
    • 2021-11-25
    • 2020-06-27
    • 2021-05-14
    • 2020-01-24
    • 2021-06-29
    • 2021-08-09
    • 2021-11-14
    • 2021-10-13
    相关资源
    最近更新 更多