Skip to content

Conversation

@shunn2
Copy link

@shunn2 shunn2 commented Oct 26, 2025

Summary

This PR fixes an issue where useSWRMutation does not await async onSuccess or onError callbacks.
Previously, when developers provided an async callback (for example, revalidating data with mutate(key)), it was executed in parallel with the return of trigger(), leading to race conditions and unhandled promise rejections.

Now, async callbacks are awaited safely, preventing unhandled rejections while maintaining backward compatibility.

Example

const { trigger } = useSWRMutation('/api/item', updateItem, {
  onSuccess: async () => {
    await mutate('/api/item') // unhandled rejection if this fails
  }
})

await trigger({ id: 1 })

Fix

  • Await onSuccess and onError callbacks inside trigger().
  • Wrap both in try/catch to prevent callback errors from propagating.
  • Log callback errors to console.error for visibility.
  • Preserve existing behavior:
  • The mutation result and UI state remain unchanged even if a callback fails.
  • No breaking change for synchronous callbacks.

Related Issue: #4171

@shunn2 shunn2 requested review from huozhi and shuding as code owners October 26, 2025 16:14
@codesandbox-ci
Copy link

This pull request is automatically built and testable in CodeSandbox.

To see build info of the built libraries, click here or the icon next to each commit SHA.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant