fix: useRequest 请求序号防竞态 + ty-crud 搜索/重置去重

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
liuyun 2026-10-11 16:46:13 +08:00
parent ed1a1e115c
commit 77c9c3fd25
2 changed files with 16 additions and 5 deletions

View File

@ -173,13 +173,20 @@ watch([page, pageSize], () => {
}) })
function handleSearch(): void { function handleSearch(): void {
page.value = 1 resetAndFetch()
fetchList()
} }
function handleReset(): void { function handleReset(): void {
page.value = 1 resetAndFetch()
}
/** 重置到第一页并查询:page 已是 1 时 watch 不触发,需手动查询,避免重复请求。 */
function resetAndFetch(): void {
if (page.value === 1) {
fetchList() fetchList()
} else {
page.value = 1
}
} }
async function openCreate(): Promise<void> { async function openCreate(): Promise<void> {

View File

@ -47,10 +47,12 @@ export function useRequest<TData, TParams extends unknown[]>(
let lastParams: TParams = defaultParams let lastParams: TParams = defaultParams
let controller: AbortController | null = null let controller: AbortController | null = null
let seq = 0
async function run(...args: TParams): Promise<TData | undefined> { async function run(...args: TParams): Promise<TData | undefined> {
controller?.abort() controller?.abort()
controller = new AbortController() controller = new AbortController()
const mySeq = ++seq
lastParams = args.length > 0 ? args : lastParams lastParams = args.length > 0 ? args : lastParams
loading.value = true loading.value = true
@ -59,16 +61,18 @@ export function useRequest<TData, TParams extends unknown[]>(
try { try {
const result = await fetcher(...lastParams, controller.signal) const result = await fetcher(...lastParams, controller.signal)
if (mySeq !== seq) return undefined // 已被更新的请求取代
data.value = result data.value = result
options.onSuccess?.(result, lastParams) options.onSuccess?.(result, lastParams)
return result return result
} catch (e) { } catch (e) {
if (isCanceled(e)) return undefined if (isCanceled(e)) return undefined
if (mySeq !== seq) return undefined
error.value = e error.value = e
options.onError?.(e, lastParams) options.onError?.(e, lastParams)
return undefined return undefined
} finally { } finally {
loading.value = false if (mySeq === seq) loading.value = false
options.onFinally?.(lastParams) options.onFinally?.(lastParams)
} }
} }