JavaScriptの「Illegal invocation」の直し方
JavaScript で TypeError: Illegal invocation が出るのは、ブラウザに組み込まれたメソッドを、元のオブジェクトから切り離して呼んだときです。document.querySelector.bind(document) のように、呼ぶときの this を元のオブジェクトに固定すると、エラーは消えます。
document.querySelector を $ のような短い名前の変数に入れたときや、API クライアントのクラスに fetch をプロパティとして持たせたときに出ます。私は検証環境でこのエラーを起こし、直したあとに消えることを確かめました。
検証環境は Ubuntu 24.04 です。ブラウザは Playwright 1.63.0 から動かした Chromium 158 で、ページは検証環境で動かした HTTP サーバー(http://127.0.0.1:8080/)から配信しました。Node.js は 24.22.3 と 22.23.5 で試しています。Node.js のコマンドは、実際にはバージョンごとの node をフルパスで指定して実行しましたが、記事では node と書いています。Firefox と Safari は試していません。出力の中の検証環境の作業フォルダーは /path/to/app に置き換えています。
エラーの全文
次の query.js を、<script type="module"> で読み込むページを用意しました。document.querySelector を $ という短い名前で呼べるように、変数に入れています。
// document.querySelector を短い名前で使いたくて、変数に入れた
const $ = document.querySelector;
const title = $('h1');
document.getElementById('out').textContent = title.textContent;
Chromium でページを開くと、4行目で次のエラーが出て、そこから先は動きませんでした。
TypeError: Illegal invocation
at http://127.0.0.1:8080/query.js:4:15
ページの error イベントで受け取ったメッセージは Uncaught TypeError: Illegal invocation でした。:4:15 は、4行目の $('h1') を指しています。
fetch の場合は、メッセージにメソッドの名前が入ります。次の api.js は、テストのときに fetch を差し替えられるようにした、小さな API クライアントです。
// fetch を差し替えられるようにした、小さな API クライアント
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;
このページでは、7行目の this.fetch(path) で次のエラーになりました。
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
なぜ「Illegal invocation」になるのか
JavaScript のメソッドの this は、呼んだときの書き方で決まります。document.querySelector('h1') と書けば this は document です。ところが、変数に入れて $('h1') と呼ぶと、this は document ではなくなります。this.fetch(path) の場合は、this が window ではなく ApiClient のインスタンスになります。
querySelector や fetch のようなブラウザの組み込みのメソッドは、this が決まった種類のオブジェクトでないと動きません。MDN の「called on incompatible type」のエラーの解説には、関数が期待していない this で呼ばれたときに出るエラーとして、V8 の TypeError: Illegal invocation が挙がっています。同じページによると、Firefox では 'addEventListener' called on an object that does not implement interface EventTarget. のような文面になります。
Chromium では、ほかのメソッドでも同じでした。ページの中で1つずつ実行した結果です(左が実行したコード、右が結果です)。
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
const { querySelector } = document のような分割代入も、変数に入れるのと同じで、エラーになります。map などにメソッドをそのまま渡した場合も、map の中から呼ばれるときに this が document にならないので、エラーになりました。
直し方:this を元のオブジェクトに固定する
直し方は3つあり、どれも Chromium でエラーが消えました。
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
1つ目の bind() は、this を指定した値にした新しい関数を作ります。2つ目のアロー関数は、中で document.querySelector(sel) と普通に呼び直しているので、this は document です。3つ目の call() は、呼ぶたびに this の値を渡して関数を呼び出します。変数に入れて何度も使うなら、1つ目か2つ目が書きやすいです。
最初の query.js の2行目を bind に直すと、エラーは出なくなり、ページに「見出し」と表示されました。
// bind で、this を document に固定した関数を作る
const $ = document.querySelector.bind(document);
API クライアントのほうは、api.js の4行目を次のように変えると、エラーが消え、data.json の「取得できました」が表示されました。
this.fetch = options.fetch ?? window.fetch.bind(window);
map に渡す場合は、アロー関数で包むか、map の2つ目の引数に document を渡します。2つ目の引数は、コールバックを呼ぶときの this になります。
['h1', 'p'].map((sel) => document.querySelector(sel).tagName).join(',') => H1,P
['h1', 'p'].map(document.querySelector, document).map((el) => el.tagName).join(',') => H1,P
固定する相手は、メソッドを取り出したオブジェクトと同じ種類にします。要素にも同じ名前の querySelector がありますが、document.querySelector を document.body に bind しても、エラーは消えませんでした。
const qs = document.querySelector.bind(document.body); String(qs('h1')) => TypeError: Illegal invocation
setTimeout や fetch は、変数に入れただけなら動く
setTimeout と fetch は、変数に入れて呼ぶだけならエラーになりませんでした。エラーになったのは、オブジェクトのプロパティにして、そのオブジェクトから呼んだときです。
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'); 'エラーなし' => エラーなし
o.fetch(...) と呼ぶと、this が o になります。上の ApiClient で this.fetch(path) がエラーになったのも、これと同じです。console.log は、変数に入れて呼んでもエラーになりませんでした。
Node.js では文面が違うことがある
Node.js でも、performance.now と Headers の get を切り離して呼ぶとエラーになりました。ただ、メッセージが「Illegal invocation」にならないものがありました。performance.now を変数に入れて呼ぶと、Node.js 24.22.3 では次のように出て止まりました(終了コードは1)。
$ 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
このあとに Node.js の内部を指す3行と、code: 'ERR_INVALID_THIS'、Node.js v24.22.3 の行が続きます(ここでは省きました)。Chromium で同じことをしたときは Illegal invocation でした。Node.js でも、performance.now.bind(performance) にするとエラーは消え、数値が返りました。
一方、Headers の get を変数に入れて呼んだときは、Node.js でも TypeError: Illegal invocation になりました。エラーの code は ERR_INVALID_THIS です。headers.get.call(headers, 'content-type') にすると、application/json が返りました。Node.js 22.23.5 でも、どちらも同じメッセージでした。
ERR_INVALID_THIS が出たときも、原因と直し方は「Illegal invocation」と同じです。Node.js のエラーコードの一覧にも、Node.js の API 関数が合わない this で呼ばれたときのエラーだと書かれています。





