From 381dc3c2cd7cf1b6e1277afee8e71b0921c6aa03 Mon Sep 17 00:00:00 2001 From: shunn2 Date: Mon, 27 Oct 2025 01:09:39 +0900 Subject: [PATCH] fix: await async onSuccess/onError callbacks to prevent unhandled rejections --- src/mutation/index.ts | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/mutation/index.ts b/src/mutation/index.ts index 363c2138b..980709630 100644 --- a/src/mutation/index.ts +++ b/src/mutation/index.ts @@ -86,7 +86,12 @@ const mutation = (() => startTransition(() => setState({ data, isMutating: false, error: undefined }) ) - options.onSuccess?.(data as Data, serializedKey, options) + // Await onSuccess to ensure async operations complete before returning + try { + await options.onSuccess?.(data as Data, serializedKey, options) + } catch (error) { + console.error('[SWR] onSuccess callback error:', error) + } } return data } catch (error) { @@ -96,7 +101,16 @@ const mutation = (() => startTransition(() => setState({ error: error as Error, isMutating: false }) ) - options.onError?.(error as Error, serializedKey, options) + // Await onError to ensure async operations complete + // Wrap in try-catch to prevent nested error handling + try { + await options.onError?.(error as Error, serializedKey, options) + } catch (nestedError) { + // onError callback errors should not interfere with error handling + if (typeof console !== 'undefined' && console.error) { + console.error('[SWR] onError callback error:', nestedError) + } + } if (options.throwOnError) { throw error as Error }