这是代码...您将如何中止此类 ajax 调用?
或者,如何防止 React 给出错误“在未安装的组件上调用 setState”?
(httpGet 只是 XMLHttpRequest 的包装和 promise )
async componentDidMount() {
const response = await httpGet("/ajaxRequest");
if(response) {
//the component has already been unmounted
this.setState(() => ({success: true}));
}
}
componentWillUnmount() {
//should abort possible running ajax
}
编辑: 这是包装器:
const httpGet = function (url) {
const request = new XMLHttpRequest;
request.open("GET", url, true);
return new Promise((resolve, reject) => {
request.onload(response => {
resolve(response);
});
request.onerror(() => {
reject("Network error");
});
request.send();
});
};
最佳答案
为了能够随时中止它,XMLHttpRequest 包装器应该:
要么使用 Promise 返回请求对象本身。
或者在包装器外部创建请求。
或者使用 sub/pub 库(如 mufa 或 redux)。
我会选择第二个选项
const httpGet = function (url, request = new XMLHttpRequest()) { // 2 arguments 👈🏼
request.open("GET", url, true);
return new Promise((resolve, reject) => {
request.onload(response => {
resolve(response);
});
request.onerror(() => {
reject("Network error");
});
request.send();
});
};
现在在componentDidMount
中:
async componentDidMount() {
this.request = new XMLHttpRequest();
const response = await httpGet("/ajaxRequest", this.request);
if(response) {
//the component has already been unmounted
this.setState(() => ({success: true}));
}
}
现在在componentWillUnmount
中:
componentWillUnmount() {
if (this.request && this.request.abort) {
this.request.abort();
}
}
就这么简单。 如果您不想中止,那么您的第一个包装器 (httpGet) 仍然有效,因为第二个参数(请求)是可选的。
关于javascript - 如何在 componentWillUnmount 中中止运行 async/await xmlHttpRequest?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47463048/