【发布时间】:2018-12-19 00:24:52
【问题描述】:
如果我的componentDidMount 生命周期中有一个 api
constructor() {
this.source = axios.CancelToken.source();
}
componentDidMount() {
axios.get('some-api-url', {
cancelToken: this.source.token,
});
.then(res => {
// set state here or do something based on response i get
})
.catch(error => {
// handle error
})
}
componentWillUnmount() {
this.source.cancel('request cancelled');
}
回到我的问题,为什么我必须这样做,只是为了避免这个错误;
警告:无法在未安装的组件上调用 setState(或 forceUpdate)。这是一个空操作,但它表明您的应用程序中存在内存泄漏。要修复,请在 componentWillUnmount 方法中取消所有订阅和异步任务。
如果我只是加载这个组件而我什至没有以任何方式卸载该组件,为什么它仍然被卸载。
我正在使用 react 路由器,每次使用我切换页面时都会收到 setState 错误。为什么我会收到此错误?为什么必须取消componentDidUnmount中的ajax调用的所有订阅?
【问题讨论】:
-
能否包含您的 React Router 代码以显示您如何使用此组件?
标签: ajax reactjs xmlhttprequest axios