问题描述:在React Native开发中,假如在一个屏幕中有一个异步请求,当用户切换到其他屏幕时,如果请求还未完成,可能会导致“Alert async in view”问题的出现。
import { Component } from 'react';
class MyComponent extends Component {
_isMounted = false;
componentDidMount() {
this._isMounted = true;
// 异步请求示例
fetchData().then(data => {
if (this._isMounted) {
// 在组件卸载之前检查标志位
alert(data);
}
});
}
componentWillUnmount() {
this._isMounted = false;
}
render() {
// 组件渲染方法
return null;
}
}