运行代码时,出现此错误,这将导致代码执行失败:
无法在已卸载的组件上执行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();
});
}
});
}
答案 0 :(得分:0)
由于device.connect
是异步的,因此在卸载组件之后,有可能调用scan2函数。如果是这样,您可能不必担心内存泄漏