javascript - 应用程序中的内存泄漏
问题描述
当我运行我的代码时,我收到此错误,这将导致代码执行失败:
无法对未安装的组件执行 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();
});
}
});
}
解决方案
您的 scan2 函数可能会在您的组件卸载后被调用,因为device.connect
它是异步的。如果是这种情况,您可能不必担心内存泄漏
推荐阅读
- python - Python DataFrame:根据自定义值将数据拆分为行?
- javascript - 如果用户使用 onbefoerunload 导航,如何在 jexcel 单元格中发生更改时发出警报
- python - Keras acc 和 val_acc 不会改变
- r - 如何为 R Shiny 中的单个 fileInput() 分配不同的进程给 selectInputs() 的给定组合?
- python - 在 Python 中解决问题以在团队中分配多个项目
- angular - Ionic Cordova ngx Translate 总是在开头添加一个空格
- kubernetes - Kubernetes 集群内的子网划分
- c - CS50 拼写器 (pset5) 中的内存错误
- javascript - 将参数传递给函数回调
- .net - 基于 Stage 的 Azure Pipelines Config Transform