使用 axios 取消卸载时的异步请求

Sac*_*hta 7 reactjs axios

对于某些获取请求,我有多个带有axios插件的组件。我需要一些帮助才能在 react js 中的组件卸载事件上使用 axios 取消所有 xhr 请求。但是 axios 取消代码不起作用。它的 return me cancel() 不是函数错误。

代码示例:-

import axios from 'axios';


var CancelToken = axios.CancelToken;
var cancel;

axios.get('abc/xyz', {
  cancelToken: new CancelToken(function executor(c) {
    // An executor function receives a cancel function as a parameter
    cancel = c;
  })
});

// cancel the request
cancel();
Run Code Online (Sandbox Code Playgroud)

请帮我在 axios 中实现取消请求。

谢谢。

tas*_*enb 6

这很简单。在中创建请求componentDidMount并在中取消请求componentWillUnmount。将 url 替换为现有的 JSON 文件,此代码段将按预期工作:

class MyComponent extends Component {
  constructor (props) {
    super(props)

    this.state = {
      data: []
    }
  }

  componentDidMount () {
    this.axiosCancelSource = axios.CancelToken.source()

    axios
      .get('data.json', { cancelToken: this.axiosCancelSource.token })
      .then(response => {
        this.setState({
          data: response.data.posts
        })
      })
      .catch(err => console.log(err))
  }

  componentWillUnmount () {
    this.axiosCancelSource.cancel('Axios request canceled.')
  }

  render () {
    const { data } = this.state

    return (
     <div>
          {data.items.map((item, i) => {
            return <div>{item.name}</div>
          })}
      </div>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)


Rav*_*ala 1

除非您使用 ,否则您无法取消请求RxJS。我建议你使用 redux-observable 来达到这个目的。检查以获取更多信息。您必须takeUntil在 Epic 中使用运算符,并在取消操作触发时进行取消。这是上述资源给出的示例代码。

import { ajax } from 'rxjs/observable/dom/ajax';

const fetchUserEpic = action$ =>
  action$.ofType(FETCH_USER)
    .mergeMap(action =>
      ajax.getJSON(`/api/users/${action.payload}`)
        .map(response => fetchUserFulfilled(response))
        .takeUntil(action$.ofType(FETCH_USER_CANCELLED))
    );
Run Code Online (Sandbox Code Playgroud)