"Illegal invocation" errors in JavaScript

Published on in JavaScript

Last updated on

JavaScript throws an "Illegal invocation" error when the context of a function is lost, i.e. when the function's this keyword isn't referring to where it should.

Some context (pun intended): I tried to destructure the abort method of an AbortController, but all I got was the error:

const abortController = new AbortController()
export const { abort } = abortController

// In another file:

abort()
//=> TypeError: Illegal invocation

abort.apply(abortController)
// Now `this` refers to `abortController` again,
// so everything's ok
// (but `abortController` needs to be exported as well)

abortController.abort()
// This is ok too

This seems like a basic concept, but somehow the error message didn't ring any bells when I encountered it this week.

Firefox produces a much more descriptive error:

TypeError: 'abort' called on an object that does not implement interface AbortController.

So does iOS Safari:

TypeError: Can only call AbortController.abort on instances of AbortController

If you don't want to export the whole abort controller, you could export a separate function called abort that calls abortController.abort():

const abortController = new AbortController()
export const abort = () => abortController.abort()

// In another file:

abort() // ok

Read about "Illegal invocation" errors in JavaScript on Stack Overflow