fix(mobile): abort uni.request when the platform timeout does not fire
Some uni-app platforms ignore the `timeout` option, leaving the returned promise pending forever and hanging the calling page with no error path. Drive the deadline locally: keep a single-shot `finish` guard so success, failure and timeout can only settle once, and on timeout call `task.abort()` before rejecting so the in-flight request is released instead of leaking. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -118,8 +118,17 @@ export const apiRequest = async <T>(options: RequestOptions): Promise<T> => {
|
||||
return requestWithXhr<T>(options);
|
||||
}
|
||||
|
||||
const timeout = options.timeout || 30000;
|
||||
const response = await new Promise<any>((resolve, reject) => {
|
||||
uni.request({
|
||||
let finished = false;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
const finish = (callback: () => void) => {
|
||||
if (finished) return;
|
||||
finished = true;
|
||||
if (timer) clearTimeout(timer);
|
||||
callback();
|
||||
};
|
||||
const task = uni.request({
|
||||
url: normalizeUrl(options.url),
|
||||
method: options.method || 'GET',
|
||||
data: options.data as string | ArrayBuffer | Record<string, unknown> | undefined,
|
||||
@@ -127,10 +136,19 @@ export const apiRequest = async <T>(options: RequestOptions): Promise<T> => {
|
||||
...authHeaders(options.method !== 'GET', options.auth !== false),
|
||||
...options.header
|
||||
},
|
||||
timeout: options.timeout || 30000,
|
||||
success: resolve,
|
||||
fail: reject
|
||||
timeout,
|
||||
success: (result) => finish(() => resolve(result)),
|
||||
fail: (error) => finish(() => reject(error))
|
||||
});
|
||||
if (!finished) {
|
||||
timer = setTimeout(() => finish(() => {
|
||||
try {
|
||||
task.abort();
|
||||
} finally {
|
||||
reject(new Error('网络请求超时'));
|
||||
}
|
||||
}), timeout);
|
||||
}
|
||||
});
|
||||
|
||||
return readPayload<T>(response.statusCode, response.data, options.clearAuthOnUnauthorized !== false);
|
||||
|
||||
Reference in New Issue
Block a user