首页 > 解决方案 > 应用程序中的内存泄漏

问题描述

当我运行我的代码时,我收到此错误,这将导致代码执行失败:

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

为什么我会收到此错误?

我相信是因为以错误的方式使用 setState,但不明白为什么。

这是我的代码:

class Activity extends Component {
  constructor(props) {
    super(props);
    this.manager = new BleManager();
    this.state = {
      device1: "",
      device2: "",
      info: "",
      values: {},
      time: null,
    };
  }

  componentDidMount() {
    this.scan1()
  }


  scan1() {
    console.log(" ")
    this.manager.startDeviceScan(null, null, (error, device) => {
      if (error) {
        return;
      }
      if ((device.name == this.model_dx(this.props.Model)) || device.name == this.model_sx(this.props.Model)) {
        this.setState({device1: device.id})
        console.log("Device 1 ID: " + this.state.device1)
        this.manager.stopDeviceScan();
        device.connect({autoConnect: true})
          .then(() => {
            this.scan2();
          })
          .then(() => {
            this.deviceService1(device);
          })
          .catch(() => {
            Alert.alert("Error");
            Actions.homepage();
          });
      }
    });
  }

  scan2() {
    this.manager.startDeviceScan(null, null, (error, device) => {
      if (error) {
        return;
      }
      if ((device.name == this.model_sx(this.props.Model))|| device.name == this.model_dx(this.props.Model)) {
        this.setState({device2: device.id})
        console.log("Device 2 ID: " + this.state.device2)
        this.manager.stopDeviceScan();
        device.connect({autoConnect: true})
          .then(() => {
            prova = this.manager.isDeviceConnected(dispositivo2)
            console.log(prova)
            this.deviceService2(device);
          })
          .catch(() => {
            Alert.alert(
              "Error"
            );
            Actions.homepage();
          });
      }
    });
  }

标签: javascriptreact-native

解决方案


您的 scan2 函数可能会在您的组件卸载后被调用,因为device.connect它是异步的。如果是这种情况,您可能不必担心内存泄漏


推荐阅读