fetch-event-source icon indicating copy to clipboard operation
fetch-event-source copied to clipboard

fix: Resolve race condition in AbortController handling during tab visibility changes

Open yushihang opened this issue 8 months ago • 0 comments
trafficstars

Issue

close #95 A race condition exists in the error handling of aborted requests when rapidly switching browser tabs. This causes unnecessary request retries and incorrect error handling behavior.

Current Behavior

When switching browser tabs quickly:

  1. Request A is initiated with AbortController instance A
  2. Tab becomes hidden -> Controller A's abort() is called
  3. Tab becomes visible -> Request B starts with Controller B
  4. Request A's error handler executes but incorrectly checks Controller B's status
  5. This leads to unnecessary retries of intentionally aborted requests

Root Cause

The issue stems from using a shared global curRequestController variable across different async contexts. When error handling occurs asynchronously, it may check the abort status of a different controller instance than the one that initiated the request.

Solution

Store the AbortController instance in the function scope to ensure each request's error handling uses its own controller:

- curRequestController = new AbortController();
+ const currentController = new AbortController();
+ curRequestController = currentController;
  // Later in catch block:
- if (!curRequestController.signal.aborted)
+ if (!currentController.signal.aborted)

Impact

  • Eliminates unnecessary request retries
  • Correctly handles tab visibility changes
  • Improves error handling accuracy
  • No breaking changes to public API

Testing

Verified by:

  • Rapidly switching browser tabs
  • Confirming aborted requests don't trigger retries
  • Ensuring normal retry behavior for actual errors remains unchanged

yushihang avatar Mar 11 '25 13:03 yushihang