axios 中一个请求取消的示例:
axios 取消请求的示例代码import React, { useState, useEffect } from "react"; import axios, { AxiosResponse } from "axios"; export default function App() { const [index, setIndex] = useState(0); const [imgUrl, setImgUrl] = useState(""); useEffect(() => { console.log(`loading ${index}`); const source = axios.CancelToken.source(); axios .get("https://dog.ceo/api/breeds/image/random", { cancelToken: source.token }) .then((res: AxiosResponse<{ message: string; status: string }>) => { console.log(`${index} done`); setImgUrl(res.data.message); }) .catch(err => { if (axios.isCancel(source)) { console.log(err.message); } }); return () => { console.log(`canceling ${index}`); source.cancel(`canceling ${index}`); }; }, [index]); return ( <div> <button onClick={() => { setIndex(index + 1); }} > click </button> <div> <img src={imgUrl} alt="" /> </div> </div> ); }