取消与Axios卸载时的异步请求



我的多个组件带有AXIOS插件,以便某些GET请求。我需要一些帮助,以取消所有XHR请求,并在React JS中的组件卸载事件上使用Axios。但是Axios取消代码不起作用。它的返回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();

请帮助我在Axios中实施取消请求。

谢谢。

这很简单。在componentDidMount中创建请求,然后在componentWillUnmount中取消该请求。用现有的JSON文件替换URL,此片段将按预期工作:

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

除 @ taseenb 响应,如果您使用react钩子,这里是一个示例。

使用使用feasteffect 检测路由更改。然后,在卸下路线时,用Axios取消请求取消令牌。THTAT之后,生成新的Axios取消令牌以提出新的请求。请参阅Axios Doc有关更多详细信息(https://github.com/axios/axios)。

rout.tsx文件

import React, { useEffect } from 'react';
import { Route, RouteProps, useLocation } from 'react-router-dom';
import API from 'src/services/service';
const CustomRoute = (props: RouteProps) => {
  const location = useLocation();
  // Detect Route Change
  useEffect(() => {
    handleRouteChange();
    return () => {
      handleRouteComponentUnmount();
    };
  }, [location?.pathname]);
  function handleRouteChange() {
    // ...
  }
  function handleRouteComponentUnmount() {
    API.finishPendingRequests('RouteChange');
  }
  return <Route {...props} />;
};
export default CustomRoute;

service.ts文件

import { Response } from 'src/models/request';
import axios, {AxiosInstance, AxiosResponse } from 'axios';
const ORIGIN_URL = 'https://myserver.com'
const BASE_URL = ORIGIN_URL + '/api';
let CANCEL_TOKEN_SOURCE = axios.CancelToken.source();
    
function generateNewCancelTokenSource() {
  CANCEL_TOKEN_SOURCE = axios.CancelToken.source();
}
export const axiosInstance: AxiosInstance = axios.create({
  baseURL: BASE_URL,
});
const API = {
  get<DataResponseType = any>(
    endpoint: string,
  ): Promise<AxiosResponse<Response<DataResponseType>>> {
    return axiosInstance.get<Response<DataResponseType>>(endpoint, {
      cancelToken: CANCEL_TOKEN_SOURCE.token,
    });
  },
  // ...Other Functions
  finishPendingRequests(cancellationReason: string) {
    CANCEL_TOKEN_SOURCE.cancel(cancellationReason);
    generateNewCancelTokenSource();
  },
};
export default API;

,除非您使用 RxJS,否则不能取消请求。我建议您将Redux-Observable用于此目的。检查此信息以获取更多信息。您必须在史诗中使用takeUntil操作员,并在取消操作发射时进行取消。这是上述资源给出的示例代码。

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

使用Faxios代替Axios

 let req = faxios()
  .url('abc/xyz')
  .GET
  .then(res => {})
  .catch(err => {});
// canceling...
req.cancel();

最新更新