MeWrite Docs

TypeError: x is not a function

JavaScriptで関数ではないものを関数として呼び出した際のエラー

概要

JavaScriptで関数ではない値(undefined、オブジェクト、文字列など)を関数として呼び出そうとした際に発生するエラーです。

エラーメッセージ

TypeError: x is not a function
TypeError: undefined is not a function
TypeError: object.method is not a function

原因

  1. 変数名の重複: 関数と同名の変数を定義して上書きしてしまった
  2. メソッドの存在確認不足: オブジェクトに存在しないメソッドを呼び出した
  3. インポートの誤り: モジュールから正しくエクスポートされていない関数をインポートした
  4. thisのコンテキスト喪失: コールバックでthisが変わり、メソッドが見つからない

解決策

1. 変数名の重複を確認

1
2
3
4
5
6
7
8
9
// Bad: 関数を上書きしてしまっている
let myFunction = function() { console.log('Hello'); };
myFunction = 'string'; // 上書き
myFunction(); // TypeError: myFunction is not a function

// Good: 別名を使用
let myFunction = function() { console.log('Hello'); };
let myString = 'string';
myFunction(); // OK

2. メソッドの存在確認

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// Bad
obj.method(); // methodが存在しない場合エラー

// Good: Optional chaining
obj.method?.();

// Good: 存在確認
if (typeof obj.method === 'function') {
  obj.method();
}

3. 正しいインポート

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// module.js
export const myFunction = () => {};
export default { myFunction };

// Bad
import myFunction from './module'; // default exportを取得
myFunction(); // TypeError

// Good
import { myFunction } from './module';
myFunction(); // OK

4. thisのバインド

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class MyClass {
  constructor() {
    this.value = 42;
  }

  getValue() {
    return this.value;
  }
}

const obj = new MyClass();

// Bad
const fn = obj.getValue;
fn(); // TypeError or undefined

// Good: bindを使用
const fn = obj.getValue.bind(obj);
fn(); // 42

// Good: アロー関数でラップ
const fn = () => obj.getValue();
fn(); // 42

5. 配列メソッドの確認

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// Bad: 配列ではないものにmapを使用
const notArray = { 0: 'a', 1: 'b' };
notArray.map(x => x); // TypeError

// Good: Array.fromで変換
Array.from(notArray).map(x => x);

// Good: 配列かどうか確認
if (Array.isArray(notArray)) {
  notArray.map(x => x);
}

よくある間違い

  • setTimeout(myFunc(), 1000)setTimeout(myFunc, 1000) (括弧を付けると即時実行される)
  • IIFEの前にセミコロンを付け忘れる
  • コールバック関数を渡す際に括弧を付けてしまう

関連エラー

参考リンク

JavaScript の他のエラー

最終更新: 2025-12-13