Fetch cancellation in React Native 0.7x: AbortController rejects promptly but native socket teardown is unclear
0 reputation · 12 Oct 2020, 19:30 UTC
0 reputation · 12 Oct 2020, 19:30 UTC
I'm designing a shared networking layer for a React Native app (0.7x era, Hermes) and want fetch requests to support both explicit cancellation and a request deadline. My plan is to use AbortController for cancellation and a manual setTimeout calling controller.abort() for timeouts, since fetch itself exposes no timeout option in this environment.
I need to distinguish an AbortError rejection from genuine network failures so cancelled requests are not logged or retried as errors. What I cannot pin down is what happens underneath: after abort() rejects the JavaScript promise, does the native socket actually close, or can the request keep consuming resources (and firing progress callbacks) on the native side? Documentation suggests this may differ between Android and iOS networking stacks.
There is also a compatibility question: AbortSignal.timeout may not exist in all runtimes I target, so I need to know whether a setTimeout-based abort is equivalent.
For React Native 0.7x with Hermes, a manual setTimeout that calls controller.abort() is functionally equivalent to AbortSignal.timeout for fetch deadlines. AbortSignal.timeout is not present in RN 0.70-0.71 Hermes builds, so the polyfill is required. Once abort() is invoked, the native request is cancelled via NSURLSessionTask.cancel() on iOS and OkHttp Call.cancel() on Android. The JS promise rejects with a DOMException whose name is 'AbortError' on both platforms, and checking err.name === 'AbortError' is the reliable way to distinguish cancellation from network failures.
typeof AbortSignal.timeout === 'function'. If false, use the setTimeout polyfill.if (e.name === 'AbortError') { /* do not log or retry */ }response.body?.cancel().Assumption: you are using the built-in React Native fetch. If a custom native fetch bridge is used, AbortController wiring may be incomplete and the above guarantees do not hold.
One diagnostic detail that changes the recommendation: are you using the default RN fetch or a third-party native fetch implementation such as react-native-http-bridge? The native cancel path differs for custom bridges.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.