You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native实现加载器时报已卸载组件无法更新状态错误如何解决

你遇到的错误是因为在componentDidMount中注册的setInterval定时器没有在组件卸载时清除,定时器会持续执行回调调用setState,此时如果组件已经被销毁,就会触发该警告同时造成内存泄漏,按如下方式修改即可修复:

修复后完整代码

import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import AnimatedLoader from 'react-native-animated-loader';


export default class Loader extends React.Component {
  constructor(props) {
    super(props);
    this.state = { visible: false };
    // 存储定时器ID
    this.timerId = null;
  }

  componentDidMount() {
    // 保存定时器ID到实例属性
    this.timerId = setInterval(() => {
      // 改用函数式更新更稳妥,避免依赖外部state出现脏数据
      this.setState(prevState => ({
        visible: !prevState.visible
      }));
    }, 6000);
  }

  componentWillUnmount() {
    // 组件卸载时清除定时器
    if (this.timerId) {
      clearInterval(this.timerId);
    }
  }

  render() {
    const { visible } = this.state;
    return (
        <View backgroundColor={'black'} style={{ flex: 1, justifyContent:'center' }}>
      <AnimatedLoader
        visible={visible}
        overlayColor="white"
        source={require("./loader.json")}
        animationStyle={styles.lottie}
        speed={1}
      >
        <Text>Doing something...</Text>
      </AnimatedLoader>
      </View>
    );
  }
  
}


const styles = StyleSheet.create({
  lottie: {
    width: 100,
    height: 100
  }
});

核心修改点

  • 新增实例属性timerId存储定时器的返回ID,用于后续定位清除对应定时器
  • 新增componentWillUnmount生命周期,组件卸载前执行clearInterval清除定时器,避免后续回调执行
  • 优化setState为函数式写法,直接基于上一次的状态计算新值,避免闭包导致的旧状态引用问题

内容的提问来源于stack exchange,提问作者Cli Ad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.21 18:36:07