如何在 Axios 中取消/中止 ajax 请求

我使用 axios处理 ajax 请求,使用 reactJS + flux处理呈现 UI。在我的应用程序中有第三方时间线(reactJS 组件)。时间轴可以通过鼠标滚动来管理。应用程序发送 Ajax 请求的实际数据后,任何滚动事件。服务器处理请求的速度可能比下一个滚动事件慢。在这种情况下,应用程序可能会有几个(通常是2-3个)请求,这些请求已经被弃用,因为用户需要进一步滚动。这是一个问题,因为每次在接收新的数据时间表开始重新绘制。(因为它是 reactJS + 通量)由于这个原因,用户可以看到时间轴来回移动好几次。解决这个问题最简单的方法就是像在 jQuery中一样中止以前的 ajax 请求。例如:

    $(document).ready(
var xhr;


var fn = function(){
if(xhr && xhr.readyState != 4){
xhr.abort();
}
xhr = $.ajax({
url: 'ajax/progress.ftl',
success: function(data) {
//do something
}
});
};


var interval = setInterval(fn, 500);
);

如何在 axios中取消/中止请求?

207206 次浏览

Axios 目前不支持取消请求。有关详细信息,请参阅 this issue

更新: 取消支持在 axios v0.15中添加。

编辑: 公理取消令牌 API 基于撤回的可取消承诺提议。

更新2022: 从 v0.22.0 Axios 支持终止控制器开始,以获取 API 的方式取消请求:

例如:

const controller = new AbortController();


axios.get('/foo/bar', {
signal: controller.signal
}).then(function(response) {
//...
});
// cancel the request
controller.abort()

有一个非常不错的软件包,只有很少的几个例子可以使用,称为 axios-Cancel。 我觉得这很有帮助。 这里是链接: < a href = “ https://www.npmjs.com/package/axios- rel = “ norefrer”> https://www.npmjs.com/package/axios-cancel

这是我在节点中使用承诺的方法。轮询在发出第一个请求后停止。

 var axios = require('axios');
var CancelToken = axios.CancelToken;
var cancel;
axios.get('www.url.com',
{
cancelToken: new CancelToken(
function executor(c) {
cancel = c;
})
}
).then((response) =>{
cancel();
})
import React, { Component } from "react";
import axios from "axios";


const CancelToken = axios.CancelToken;


let cancel;


class Abc extends Component {
componentDidMount() {
this.Api();
}


Api() {
// Cancel previous request
if (cancel !== undefined) {
cancel();
}
axios.post(URL, reqBody, {
cancelToken: new CancelToken(function executor(c) {
cancel = c;
}),
})
.then((response) => {
//responce Body
})
.catch((error) => {
if (axios.isCancel(error)) {
console.log("post Request canceled");
}
});
}


render() {
return <h2>cancel Axios Request</h2>;
}
}


export default Abc;


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

const CancelToken = axios.CancelToken;
const source = CancelToken.source();
let url = 'www.url.com'




axios.get(url, {
progress: false,
cancelToken: source.token
})
.then(resp => {


alert('done')


})


setTimeout(() => {
source.cancel('Operation canceled by the user.');
},'1000')

通常,只有在启动了该实例的新 ajax 请求时,才需要取消前一个 ajax 请求并忽略它的后续响应,为此,需要执行以下操作:

例如: 从 API 获得一些注释:

// declare an ajax request's cancelToken (globally)
let ajaxRequest = null;


function getComments() {


// cancel  previous ajax if exists
if (ajaxRequest ) {
ajaxRequest.cancel();
}


// creates a new token for upcomming ajax (overwrite the previous one)
ajaxRequest = axios.CancelToken.source();


return axios.get('/api/get-comments', { cancelToken: ajaxRequest.token }).then((response) => {
console.log(response.data)
}).catch(function(err) {
if (axios.isCancel(err)) {
console.log('Previous request canceled, new request is send', err.message);
} else {
// handle error
}
});
}

使用 useEffect 钩子:

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


const fetchPost = async () => {
try {
const response = await Axios.get(`endpointURL`, {
cancelToken: ourRequest.token, // <-- 2nd step
})
console.log(response.data)
setPost(response.data)
setIsLoading(false)
} 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

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

使用 Cp 轴包装器,您可以使用三种不同类型的取消 API 中止请求:

1. 取消承诺 API (答应我) :

实时浏览器示例

 const cpAxios= require('cp-axios');
const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';
 

const chain = cpAxios(url)
.timeout(5000)
.then(response=> {
console.log(`Done: ${JSON.stringify(response.data)}`)
}, err => {
console.warn(`Request failed: ${err}`)
});
 

setTimeout(() => {
chain.cancel();
}, 500);

2. 使用中止控制器信号 API:

 const cpAxios= require('cp-axios');
const CPromise= require('c-promise2');
const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';
 

const abortController = new CPromise.AbortController();
const {signal} = abortController;
 

const chain = cpAxios(url, {signal})
.timeout(5000)
.then(response=> {
console.log(`Done: ${JSON.stringify(response.data)}`)
}, err => {
console.warn(`Request failed: ${err}`)
});
 

setTimeout(() => {
abortController.abort();
}, 500);

3. 使用一个简单的公理取消标记:

 const cpAxios= require('cp-axios');
const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=5s';


const source = cpAxios.CancelToken.source();
 

cpAxios(url, {cancelToken: source.token})
.timeout(5000)
.then(response=> {
console.log(`Done: ${JSON.stringify(response.data)}`)
}, err => {
console.warn(`Request failed: ${err}`)
});
 

setTimeout(() => {
source.cancel();
}, 500);

4. 在自定义 React hook 中的用法 (现场演示) :

import React from "react";
import { useAsyncEffect } from "use-async-effect2";
import cpAxios from "cp-axios";


/*
Note: the related network request will be aborted as well
Check out your network console
*/


function TestComponent({ url, timeout }) {
const [cancel, done, result, err] = useAsyncEffect(
function* () {
return (yield cpAxios(url).timeout(timeout)).data;
},
{ states: true, deps: [url] }
);


return (
<div>
{done ? (err ? err.toString() : JSON.stringify(result)) : "loading..."}
<button onClick={cancel} disabled={done}>
Cancel async effect (abort request)
</button>
</div>
);
}

Update

Axios v0.22.0 + 原生支持 AbortController:

const controller = new AbortController();


axios.get('/foo/bar', {
signal: controller.signal
}).then(function(response) {
//...
});
// cancel the request
controller.abort()

Starting from v0.22.0 Axios supports AbortController to cancel requests in fetch API way:

const controller = new AbortController();


axios.get('/foo/bar', {
signal: controller.signal
}).then(function(response) {
//...
});
// cancel the request
controller.abort()

取消使用 CancelToken 还可以使用 CancelToken 取消请求。

The axios cancel token API is based on the withdrawn cancelable promises proposal.

这个 API 从 v0.22.0开始就已经过时了,不应该在新的项目中使用

You can create a cancel token using the CancelToken.source factory as shown below:

import {useState, useEffect} from 'react'


export function useProfileInformation({accessToken}) {
const [profileInfo, setProfileInfo] = useState(null)


useEffect(() => {
const abortController = new AbortController()


window
.fetch('https://api.example.com/v1/me', {
headers: {Authorization: `Bearer ${accessToken}`},
method: 'GET',
mode: 'cors',
signal: abortController.signal,
})
.then(res => res.json())
.then(res => setProfileInfo(res.profileInfo))


return function cancel() {
abortController.abort()
}
}, [accessToken])


return profileInfo
}


// src/app.jsx
import React from 'react'
import {useProfileInformation} from './hooks/useProfileInformation'


export function App({accessToken}) {
try {
const profileInfo = useProfileInformation({accessToken})


if (profileInfo) {
return <h1>Hey, ${profileInfo.name}!</h1>
} else {
return <h1>Loading Profile Information</h1>
}
} catch (err) {
return <h1>Failed to load profile. Error: {err.message}</h1>
}
}