@@ -176,6 +176,7 @@ export default class Request extends Duplex implements RequestEvents<Request> {
176
176
private _triggerRead : boolean ;
177
177
declare private _jobs : Array < ( ) => void > ;
178
178
private _cancelTimeouts : ( ) => void ;
179
+ private readonly _removeListeners : ( ) => void ;
179
180
private _nativeResponse ?: IncomingMessageWithTimings ;
180
181
private _flushed : boolean ;
181
182
private _aborted : boolean ;
@@ -199,6 +200,7 @@ export default class Request extends Duplex implements RequestEvents<Request> {
199
200
this . _unproxyEvents = noop ;
200
201
this . _triggerRead = false ;
201
202
this . _cancelTimeouts = noop ;
203
+ this . _removeListeners = noop ;
202
204
this . _jobs = [ ] ;
203
205
this . _flushed = false ;
204
206
this . _requestInitialized = false ;
@@ -247,14 +249,6 @@ export default class Request extends Duplex implements RequestEvents<Request> {
247
249
return ;
248
250
}
249
251
250
- if ( this . options . signal ?. aborted ) {
251
- this . destroy ( new AbortError ( this ) ) ;
252
- }
253
-
254
- this . options . signal ?. addEventListener ( 'abort' , ( ) => {
255
- this . destroy ( new AbortError ( this ) ) ;
256
- } ) ;
257
-
258
252
// Important! If you replace `body` in a handler with another stream, make sure it's readable first.
259
253
// The below is run only once.
260
254
const { body} = this . options ;
@@ -271,6 +265,21 @@ export default class Request extends Duplex implements RequestEvents<Request> {
271
265
}
272
266
} ) ;
273
267
}
268
+
269
+ if ( this . options . signal ) {
270
+ const abort = ( ) => {
271
+ this . destroy ( new AbortError ( this ) ) ;
272
+ } ;
273
+
274
+ if ( this . options . signal . aborted ) {
275
+ abort ( ) ;
276
+ } else {
277
+ this . options . signal . addEventListener ( 'abort' , abort ) ;
278
+ this . _removeListeners = ( ) => {
279
+ this . options . signal . removeEventListener ( 'abort' , abort ) ;
280
+ } ;
281
+ }
282
+ }
274
283
}
275
284
276
285
async flush ( ) {
@@ -508,6 +517,7 @@ export default class Request extends Duplex implements RequestEvents<Request> {
508
517
// Prevent further retries
509
518
this . _stopRetry ( ) ;
510
519
this . _cancelTimeouts ( ) ;
520
+ this . _removeListeners ( ) ;
511
521
512
522
if ( this . options ) {
513
523
const { body} = this . options ;
0 commit comments