fetch-event-source
fetch-event-source copied to clipboard
fix: Resolve race condition in AbortController handling during tab visibility changes
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:
- Request A is initiated with AbortController instance A
- Tab becomes hidden -> Controller A's abort() is called
- Tab becomes visible -> Request B starts with Controller B
- Request A's error handler executes but incorrectly checks Controller B's status
- 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