我正在构建一个应用程序,它可以在我每次移动手机时获得手机的速度。我得到了此值的更新,但我还可以看到下一个警告:
警告:无法在未装入的组件上执行React状态更新。这是一个禁止操作,但它表明应用程序中存在内存泄漏。若要修复此问题,请取消componentWillUnmount方法中的所有订阅和异步任务。
为什么会发生这种情况?
我使用的代码是:
import React from 'react';
import {
Text
} from 'react-native';
import {
accelerometer,
gyroscope,
setUpdateIntervalForType,
SensorTypes
} from "react-native-sensors";
import { map, filter } from "rxjs/operators";
export class SpeedPanel extends React.Component{
constructor(props) {
super(props);
this.state = {
speed: 0,
subscription: accelerometer
}
}
getData = () => {
const self = this;
const subscription = this.state.subscription
.pipe(map(({ x, y, z }) => x + y + z), filter(speed => speed > 10))
.subscribe(
speed => {
self.setState({speed: speed})
console.log(`You moved your phone with ${speed}`)
},
error => {
console.log("The sensor is not available");
}
);
setTimeout(() => {
// If it's the last subscription to accelerometer it will stop polling in the native API
subscription.unsubscribe();
}, 1000);
}
componentDidMount() {
setUpdateIntervalForType(SensorTypes.accelerometer, 400); // defaults to 100ms
setInterval(this.getData, 400);
}
render () {
return(
<Text>
{'Hello \n'}
{this.state.speed}
</Text>
)
}
}发布于 2021-03-10 13:26:00
别担心..。我重新加载了这个应用程序,没有更多的警告出现。
https://stackoverflow.com/questions/66558455
复制相似问题