无法通过 CancelToken 取消 Axios post 请求

Cant cancel Axios post request via CancelToken

此代码取消 GET 请求但无法中止 POST 调用。
如果我先发送 GET 请求并且我不通过 abortAll 方法取消它们,它们会自行完成此令牌自行取消并且不会处理下一个请求? 我错过了什么? 谢谢,约翰

import axios from 'axios'
class RequestHandler {

 constructor(){
  this.cancelToken = axios.CancelToken;
  this.source = this.cancelToken.source();
 }

 get(url,callback){

  axios.get(url,{
   cancelToken:this.source.token,
  }).then(function(response){

        callback(response.data);

    }).catch(function(err){

        console.log(err);

    })

 }

post(url,callbackOnSuccess,callbackOnFail){
 axios.post(url,{

        cancelToken:this.source.token,

    }).then(function(response){

        callbackOnSuccess(response.data);

    }).catch(function(err){

        callbackOnFail()

    })
}

abortAll(){

 this.source.cancel();
    // regenerate cancelToken
 this.source = this.cancelToken.source();

}

}

我发现你可以这样取消post请求,我理解错了this documentation part。 在之前的代码中,我已经将 cancelToken 传递给 POST 数据请求,而不是作为 axios 设置。

import axios from 'axios'


var CancelToken = axios.CancelToken;
var cancel;

axios({
  method: 'post',
  url: '/test',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  },
  cancelToken: new CancelToken(function executor(c) {
      // An executor function receives a cancel function as a parameter
      cancel = c;
    })
}).then(()=>console.log('success')).catch(function(err){

  if(axios.isCancel(err)){

    console.log('im canceled');

  }
  else{

    console.log('im server response error');

  }

});
// this cancel the request
cancel()

也许我错了,但每个请求都应该有一个唯一的源对象。

使用 cancelToken 和 source 取消先前的 Axios 请求。

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

 // cancelToken and source declaration

 const CancelToken = axios.CancelToken;
 let source = CancelToken.source();

 source && source.cancel('Operation canceled due to new request.');

 // save the new request for cancellation
 source = axios.CancelToken.source();

 axios.post(url, postData, {
     cancelToken: source.token
 })
 .then((response)=>{
     return response && response.data.payload);
 })
 .catch((error)=>{
     return error;
 });

使用内部 componentDidMount 生命周期挂钩:

useEffect(() => {
const ourRequest = Axios.CancelToken.source() // <-- 1st step

const fetchPost = async () => {
  try {
    const response = await Axios.get(`endpointURL`, {
      cancelToken: ourRequest.token, // <-- 2nd step
    })
    } catch (err) {
    console.log('There was a problem or request was cancelled.')
  }
}
fetchPost()

return () => {
  ourRequest.cancel() // <-- 3rd step
}
}, [])

注意:对于 POST 请求,将 cancelToken 作为第三个参数传递

Axios.post(`endpointURL`, {data}, {
 cancelToken: ourRequest.token, // 2nd step
})

使用 ReactJs 的最简单实现

import axios from 'axios';

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 () {
    console.log('unmount component')
    this.axiosCancelSource.cancel('Component unmounted.')
  }

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

    return (
     <div>
          {data.items.map((item, i) => {
            return <div>{item.name}</div>
          })}
      </div>
    )
  }
}