Skip to content

Commit 381dc3c

Browse files
committed
fix: await async onSuccess/onError callbacks to prevent unhandled rejections
1 parent 0b3c2c7 commit 381dc3c

File tree

1 file changed

+16
-2
lines changed

1 file changed

+16
-2
lines changed

src/mutation/index.ts

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,12 @@ const mutation = (<Data, Error>() =>
8686
startTransition(() =>
8787
setState({ data, isMutating: false, error: undefined })
8888
)
89-
options.onSuccess?.(data as Data, serializedKey, options)
89+
// Await onSuccess to ensure async operations complete before returning
90+
try {
91+
await options.onSuccess?.(data as Data, serializedKey, options)
92+
} catch (error) {
93+
console.error('[SWR] onSuccess callback error:', error)
94+
}
9095
}
9196
return data
9297
} catch (error) {
@@ -96,7 +101,16 @@ const mutation = (<Data, Error>() =>
96101
startTransition(() =>
97102
setState({ error: error as Error, isMutating: false })
98103
)
99-
options.onError?.(error as Error, serializedKey, options)
104+
// Await onError to ensure async operations complete
105+
// Wrap in try-catch to prevent nested error handling
106+
try {
107+
await options.onError?.(error as Error, serializedKey, options)
108+
} catch (nestedError) {
109+
// onError callback errors should not interfere with error handling
110+
if (typeof console !== 'undefined' && console.error) {
111+
console.error('[SWR] onError callback error:', nestedError)
112+
}
113+
}
100114
if (options.throwOnError) {
101115
throw error as Error
102116
}

0 commit comments

Comments
 (0)