简体   繁体   English

无法通过 CancelToken 取消 Axios 发布请求

[英]Cant cancel Axios post request via CancelToken

This code cancel GET requests but cant abort POST calls.此代码取消 GET 请求但无法中止 POST 调用。
If i send GET requests first and i dont cancel them via abortAll method,they just finish by themselves this token cancel by itself and doesnt work on next requests?如果我先发送 GET 请求并且我不通过abortAll方法取消它们,它们会自行完成此令牌自行取消并且不会处理下一个请求? What am i missing?我错过了什么? Thanks,John谢谢,约翰

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

}

}

I have found out that you can cancel post request this way,i missunderstand this documentation part . 我发现你可以通过这种方式取消发帖请求,我很想念这个文档部分 In previous code,i have passed cancelToken to the POST data request not as a axios setting. 在之前的代码中,我已将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()

Using inside componentDidMount lifecycle hook:使用内部 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
}
}, [])

Note: For POST request, pass cancelToken as 3rd argument注意:对于 POST 请求,将 cancelToken 作为第三个参数传递

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

Simplest implementation using ReactJs使用 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>
    )
  }
}

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

Cancel previous Axios request on new request with cancelToken and source. 使用cancelToken和source在新请求中取消先前的Axios请求。

https://github.com/axios/axios#cancellation 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;
 });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM