React Native报错TypeError: undefined is not an object (evaluating 'appState.remove')如何解决

你遇到的报错TypeError: undefined is not an object (evaluating 'appState.remove')由以下几个问题共同导致:
问题原因
- API适配错误:你使用的是新版React Native,AppState已经废弃了全局
removeEventListener方法。新API规则为:调用AppState.addEventListener会返回一个订阅实例,需要先存储这个实例,后续调用实例自带的remove()方法取消监听,你没有存储订阅实例就直接调用remove方法,就会触发undefined报错。 - 监听逻辑完全颠倒:你在组件挂载完成的
componentDidMount生命周期执行移除监听操作,在组件即将卸载的componentWillUnmount生命周期执行添加监听操作,逻辑完全错误。 - 存在冗余无效代码:
componentWillUnmount中调用_getLocationAsync没有任何实际意义,还可能引发内存泄漏。
修复后可直接运行的代码
constructor(props) { super(props); this.state = { region: null, status: undefined, appState: AppState?.currentState, modalVisible: true, isLoading: true, }; // 新增属性存储AppState订阅实例 this.appStateSub = null; this._getLocationAsync(); } componentDidMount() { // 组件挂载时添加监听,存储返回的订阅实例 this.appStateSub = AppState.addEventListener("change", this.handleAppStateChange); } handleAppStateChange = (nextAppState) => { if ( this.state.appState.match(/inactive|background/) && nextAppState === "active" ) { this._getLocationAsync(); } this.setState({ appState: nextAppState }); }; componentWillUnmount() { // 组件卸载时调用订阅实例的remove方法取消监听 this.appStateSub?.remove(); } _getLocationAsync = async () => { let { status } = await Location.requestPermissionsAsync(); let location = await Location.getCurrentPositionAsync({ enableHighAccuracy: false, timeout: 10000, maximumAge: 0, }); let region = { latitude: location.coords.latitude, longitude: location.coords.longitude, latitudeDelta: 0.0045, longitudeDelta: 0.0045, }; this.props.callback({ latitude: region.latitude, longitude: region.longitude, }); this.setState({ region: region, status: status }); };
内容的提问来源于stack exchange,提问作者Emily
相关产品推荐
相关产品推荐

