反应中止/取消AJAX请求。Axios或XHR

Dan*_*ink 4 javascript ajax reactjs

我只是开发一个SPA,并且需要我通过react componentDidMount发送到我的服务器端(节点)的异步请求提供帮助。查询有效,但是如果我快速切换到其他页面,则ajax响应中的setState函数仍在运行。尽管未安装组件。

只能更新已安装或正在安装的组件。这通常意味着您在未安装的组件上调用了setState()。这是无人值守。请检查未定义组件的代码。

为避免此错误,如果这是正确的方法,我想中止/取消在componentWillUnmount上发送的请求。

我尝试使用xml和axios进行此操作,但是它不起作用。我希望你有一个对我有用的榜样。我为其他请求方法(例如提取或其他方法)开放。

该代码看起来像这样(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
}
Run Code Online (Sandbox Code Playgroud)

Jay*_*444 6

Axios可以选择取消请求:

https://github.com/axios/axios#cancellation

防止setState在组件卸载后触发某种回调的另一种方法是让本地布尔变量存储是否已安装组件,即

componentDidMount(){
   this._mounted = true;
}

componentWillUnmount() {
   this._mounted = false;
}
Run Code Online (Sandbox Code Playgroud)

然后在axios回调中,_mounted在尝试调用之前检查是否为truesetState()