javascript - 如何在 componentWillUnmount 中中止运行 async/await xmlHttpRequest?

标签 javascript ajax reactjs async-await ecmascript-2017

这是代码...您将如何中止此类 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/

相关文章:

reactjs - 如何在 React 中为图像创建简单的旋转动画

javascript - 为什么 React JS 会发生这种情况?

reactjs - 资源音频文件无法在 Expo 中播放

javascript - 使用javascript从github页面服务器读取Json文件

javascript - 重写基本的 AngularJS (1.4) 代码以解决重大变化

javascript - 单击按钮并在 jquery 中检测其状态

php - 从 mysql 数据库加载标记并在 Google map 上显示为标记

javascript - 无法使用 JavaScript 在 HTML 表中放置带有事件监听器的按钮

asp.net - 从 ASMX 返回 JSON,并在 Javascript 中正确处理它

javascript - 即使使用 'load',div 也不会重新加载更改的内容