Skip to content

Commit

Permalink
fix: 🧩 fix axiosCancel bug
Browse files Browse the repository at this point in the history
  • Loading branch information
limuen committed Jun 27, 2024
1 parent 867d7ba commit 868bd8a
Show file tree
Hide file tree
Showing 3 changed files with 4,098 additions and 15,145 deletions.
22 changes: 16 additions & 6 deletions packages/request/helper/axiosCancel.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,18 @@
import { CustomAxiosRequestConfig } from "../index";
import qs from "qs";

// 声明一个 Map 用于存储每个请求的标识 和 取消函数
// 声明一个 Map 用于存储每个请求的标识和取消函数
let pendingMap = new Map<string, AbortController>();

// 序列化参数
export const getPendingUrl = (config: CustomAxiosRequestConfig) =>
[config.method, config.url, config.data, config.params].join("&");
// 序列化参数,确保对象属性顺序一致
const sortedStringify = (obj: any) => {
return qs.stringify(obj, { arrayFormat: "repeat", sort: (a, b) => a.localeCompare(b) });
};

// 获取请求的唯一标识
export const getPendingUrl = (config: CustomAxiosRequestConfig) => {
return [config.method, config.url, sortedStringify(config.data), sortedStringify(config.params)].join("&");
};

export class AxiosCanceler {
/**
Expand All @@ -28,9 +35,12 @@ export class AxiosCanceler {
*/
removePending(config: CustomAxiosRequestConfig) {
const url = getPendingUrl(config);
// 如果在 pending 中存在当前请求标识,需要取消当前请求
// 如果在 pending 中存在当前请求标识,需要取消当前请求并删除条目
const controller = pendingMap.get(url);
controller && controller.abort();
if (controller) {
controller.abort();
pendingMap.delete(url);
}
}

/**
Expand Down
4 changes: 3 additions & 1 deletion packages/request/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,14 @@
"antd": "^5.15.3",
"axios": "^1.6.0",
"nprogress": "^0.2.0",
"react": "^18.2.0"
"react": "^18.2.0",
"qs": "^6.11.2"
},
"devDependencies": {
"@types/nprogress": "^0.2.0",
"@types/react": "^18.2.66",
"@types/react-dom": "^18.2.19",
"@types/qs": "^6.9.11",
"@limuen/tsconfig": "workspace:*"
}
}
Loading

0 comments on commit 868bd8a

Please sign in to comment.