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

时间:2017-11-23 20:45:42

标签: javascript ajax reactjs async-await ecmascript-2017

这是代码......你怎么会中止这样的ajax调用?

或者,如何防止反应给我一个错误" setState调用unmounted组件"?

(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();
    });
};

1 个答案:

答案 0 :(得分:3)

为了能够随时中止它,XMLHttpRequest包装器应该:

  • 使用promise返回请求对象本身。

  • 或在包装器外创建请求。

  • 或使用sub / pub库(如mufa或redux)。

我会选择第二个选项

void interruptHandler(void) {
    /* Callback attached to 3rd party device driver, indicating hardware fault */
    /* Set global variable bit masked flag to indicate interrupt */
    faultsBitMask |= 0x1;
}

void auditPoll(*faults) {
    *faults = faultsBitMask;
    /* !!! Need to prevent interrupt pre-empt here !!! */
    /* Combine these two lines to a single read-modify-write? */
    faultsBitMask = 0;
}

现在在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

就这么简单。 如果你不想中止,那么你的第一个包装器(httpGet)仍然有效,因为第二个参数(request)是可选的。