日本語

How to Fix “Illegal invocation” in JavaScript

​​JavaScript​Chromium,Node.js,Troubleshooting

The TypeError: Illegal invocation in JavaScript appears when you call a method built into the browser after detaching it from its original object. If you fix the value of this to the original object when calling, such as with document.querySelector.bind(document), the error goes away.

It appears when you store document.querySelector in a short variable like $, or when an API client class holds fetch as a property. I reproduced this error in my test environment, and confirmed that it went away after I fixed the code.

Note

The test environment was Ubuntu 24.04. For the browser, I used Chromium 158 launched from Playwright 1.63.0, and the page was served from an HTTP server in the test environment (http://127.0.0.1:8080/). I tested with Node.js 24.22.3 and 22.23.5. For Node.js commands, I actually ran each version's node by its full path, but this article writes it as node. I did not test Firefox or Safari. I replaced the test environment's working folder in the output with /path/to/app.

The full error

I prepared a page that loads the following query.js with <script type="module">. I stored document.querySelector in a variable so it could be called with the short name $.

js
// I stored document.querySelector in a variable so I could use a shorter name.
const $ = document.querySelector;

const title = $('h1');
document.getElementById('out').textContent = title.textContent;

When I opened the page in Chromium, the following error occurred on line 4, and nothing after that ran.

text
TypeError: Illegal invocation
    at http://127.0.0.1:8080/query.js:4:15

The message I received in the page's error event was Uncaught TypeError: Illegal invocation. :4:15 points to $('h1') on line 4.

With fetch, the message includes the method name. The following api.js is a small API client that lets fetch be replaced during testing.

js
// A small API client where fetch can be swapped out.
class ApiClient {
  constructor(options = {}) {
    this.fetch = options.fetch ?? window.fetch;
  }
  async getJson(path) {
    const res = await this.fetch(path);
    return res.json();
  }
}

const client = new ApiClient();
const data = await client.getJson('./data.json');
document.getElementById('out').textContent = data.message;

On this page, line 7, this.fetch(path), produced the following error.

text
TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
    at ApiClient.getJson (http://127.0.0.1:8080/api.js:7:28)
    at http://127.0.0.1:8080/api.js:13:27

Why "Illegal invocation" happens

The value of this in a JavaScript method is decided by how the method is called. If you write document.querySelector('h1'), this is document. But if you store it in a variable and call $('h1'), this is no longer document. In the case of this.fetch(path), this is an instance of ApiClient, not window.

Built-in browser methods such as querySelector and fetch only work when this is a specific kind of object. MDN's explanation of the "called on incompatible type" error lists V8's TypeError: Illegal invocation as an error that occurs when a function is called with an unexpected this. According to the same page, Firefox uses a message like 'addEventListener' called on an object that does not implement interface EventTarget.

In Chromium, other methods behaved the same way. These are the results of running each line one at a time on the page (the code is on the left, the result is on the right).

text
const qs = document.querySelector; qs('h1')  =>  TypeError: Illegal invocation
const { querySelector } = document; querySelector('h1')  =>  TypeError: Illegal invocation
const now = performance.now; now()  =>  TypeError: Illegal invocation
const add = document.body.classList.add; add('x')  =>  TypeError: Illegal invocation
const enc = new TextEncoder(); const encode = enc.encode; encode('a')  =>  TypeError: Illegal invocation
['h1', 'p'].map(document.querySelector)  =>  TypeError: Illegal invocation

Destructuring such as const { querySelector } = document gives the same error as storing the method in a variable. Passing a method directly to map also failed. When map calls it, this is not document, so the error occurred.

The fix: fix this to the original object

There are three ways to fix it, and each one removed the error in Chromium.

text
const qs = document.querySelector.bind(document); qs('h1').tagName  =>  H1
const qs = (sel) => document.querySelector(sel); qs('h1').tagName  =>  H1
const qs = document.querySelector; qs.call(document, 'h1').tagName  =>  H1

The first, bind(), creates a new function whose this is the value you specify. The second, an arrow function, calls document.querySelector(sel) normally inside its body, so this is document. The third, call(), calls the function and passes the value of this each time. If you will use the stored function many times, the first or second form is easier to write.

When I changed line 2 of the original query.js to use bind, the error went away, and the page showed the text "Heading".

js
// Creates a function with this fixed to document using bind.
const $ = document.querySelector.bind(document);

For the API client, I changed line 4 of api.js as follows. The error went away, and the message "Fetched successfully" from data.json was displayed.

js

this.fetch = options.fetch ?? window.fetch.bind(window);

When passing the method to map, wrap it in an arrow function, or pass document as the second argument of map. The second argument becomes the this used when the callback is called.

text
['h1', 'p'].map((sel) => document.querySelector(sel).tagName).join(',')  =>  H1,P
['h1', 'p'].map(document.querySelector, document).map((el) => el.tagName).join(',')  =>  H1,P

Fix this to the same kind of object the method was taken from. Elements also have a method named querySelector, but binding document.querySelector to document.body did not remove the error.

text
const qs = document.querySelector.bind(document.body); String(qs('h1'))  =>  TypeError: Illegal invocation

setTimeout and fetch work when stored in a variable

Storing setTimeout and fetch in a variable and calling them did not cause an error. The error occurred only when I made them properties of an object and called them through that object.

text
const st = setTimeout; typeof st(() => {}, 0)  =>  number
const o = { st: setTimeout }; o.st(() => {}, 0)  =>  TypeError: Illegal invocation
const f = fetch; f('./data.json') instanceof Promise  =>  true
const o = { fetch }; o.fetch('./data.json')  =>  TypeError: Failed to execute 'fetch' on 'Window': Illegal invocation
const log = console.log; log('ok'); 'エラーなし'  =>  エラーなし

When you call o.fetch(...), this becomes o. The error from this.fetch(path) in ApiClient above has the same cause. console.log did not cause an error even when stored in a variable and called.

In Node.js, the message can be different

Node.js also threw errors when I called performance.now and the get method of Headers detached from their objects. However, for some of them the message was not "Illegal invocation". When I stored performance.now in a variable and called it, Node.js 24.22.3 printed the following and stopped (exit code 1).

text
$ node now.mjs
node:internal/perf/performance:138
    validateThisInternalField(this, kPerformanceBrand, 'Performance');
    ^

TypeError [ERR_INVALID_THIS]: Value of "this" must be of type Performance
    at now (node:internal/perf/performance:138:5)
    at file:///path/to/app/now.mjs:3:13

After this come three lines pointing into Node.js internals, a code: 'ERR_INVALID_THIS' line, and a Node.js v24.22.3 line (omitted here). The same test in Chromium gave Illegal invocation. In Node.js, performance.now.bind(performance) also removed the error and returned a number.

When I stored the get method of Headers in a variable and called it, Node.js also gave TypeError: Illegal invocation, with the error code set to ERR_INVALID_THIS. Using headers.get.call(headers, 'content-type') returned application/json. Node.js 22.23.5 gave the same messages for both.

When ERR_INVALID_THIS appears, the cause and the fix are the same as for "Illegal invocation". The Node.js error codes list also describes it as the error for when a Node.js API function is called with an incompatible this.

​Posted by 86