在组件卸载之前取消正在进行的异步请求或注册的事件监听器,以避免在未挂载的组件上进行更新。可以在组件的 componentWillUnmount 生命周期方法中进行解绑或清除操作。
示例代码:
class MyComponent extends React.Component { constructor() { super(); this.state = { data: null }; }
componentDidMount() { this.getData(); }
componentWillUnmount() { // 在组件卸载前取消 getData 方法的异步请求 this.source.cancel(); }
async getData() { this.source = axios.CancelToken.source(); try { const response = await axios.get('/api/data', { cancelToken: this.source.token }); this.setState({ data: response.data }); } catch (error) { if (axios.isCancel(error)) { console.log('取消了请求'); } else { console.error(error.message); } } }
render() { return (