【发布时间】:2017-10-26 08:57:19
【问题描述】:
我刚刚开发了一个 SPA,需要帮助处理我通过 react componentDidMount 发送到我的服务器端(节点)的异步请求。查询有效,但如果我快速切换到不同的页面,ajax 响应中的 setState 函数仍在运行。虽然组件已卸载。
只能更新已安装或正在安装的组件。这通常意味着 您在未安装的组件上调用了 setState() 。这是一个无操作。 请检查未定义组件的代码。
为避免此错误,如果这是正确的方法,我想中止/取消我在 componentWillUnmount 上发送的请求。
我用 xml 和 axios 试过这个,但它不起作用。我希望你有一个适合我的例子。我对 fetch 等其他请求方法持开放态度。
代码看起来像这样(Axios),但它不会取消请求:
import * as React from 'react';
import axios from 'axios';
let CancelToken = axios.CancelToken;
let source = CancelToken.source();
class MakeAjaxRequest extends React.Component {
constructor() {
super();
this.state = {
data: {}
}
}
componentDidMount() {
const that = this;
axios.get('/user/12345', {
cancelToken: source.token
})
.then(function (response) {
if (axios.isCancel(response)) {
console.log('Request canceled', response);
} else {
that.setState({
data: response.data
});
}
})
.catch(function (thrown) {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
// handle error
}
});
}
componentWillUnmount() {
source.cancel('Operation canceled by the user.');
}
//....other stuff, like render the data
}
【问题讨论】:
标签: javascript ajax reactjs