Is not a function javascript в чем ошибка

Время на прочтение
5 мин

Количество просмотров 397K

JavaScript может быть кошмаром при отладке: некоторые ошибки, которые он выдает, могут быть очень трудны для понимания с первого взгляда, и выдаваемые номера строк также не всегда полезны. Разве не было бы полезно иметь список, глядя на который, можно понять смысл ошибок и как исправить их? Вот он!

Ниже представлен список странных ошибок в JavaScript. Разные браузеры могут выдавать разные сообщения об одинаковых ошибках, поэтому приведено несколько примеров там, где возможно.

Как читать ошибки?

Перед самим списком, давайте быстро взглянем на структуру сообщения об ошибке. Понимание структуры помогает понимать ошибки, и вы получите меньше проблем, если наткнетесь на ошибки, не представленные в этом списке.

Типичная ошибка из Chrome выглядит так:

Uncaught TypeError: undefined is not a function

Структура ошибки следующая:

  1. Uncaught TypeError: эта часть сообщения обычно не особо полезна. Uncaught значит, что ошибка не была перехвачена в catch, а TypeError — это название ошибки.
  2. undefined is not a function: это та самая часть про ошибку. В случае с сообщениями об ошибках, читать их нужно прямо буквально. Например, в этом случае, она значит то, что код попытался использовать значение undefined как функцию.

Другие webkit-браузеры, такие как Safari, выдают ошибки примерно в таком же формате, как и Chrome. Ошибки из Firefox похожи, но не всегда включают в себя первую часть, и последние версии Internet Explorer также выдают более простые ошибки, но в этом случае проще — не всегда значит лучше.

Теперь к самим ошибкам.

Uncaught TypeError: undefined is not a function

Связанные ошибки: number is not a function, object is not a function, string is not a function, Unhandled Error: ‘foo’ is not a function, Function Expected

Возникает при попытке вызова значения как функции, когда значение функцией не является. Например:

var foo = undefined;
foo();

Эта ошибка обычно возникает, если вы пытаетесь вызвать функцию для объекта, но опечатались в названии.

var x = document.getElementByID('foo');

Несуществующие свойства объекта по-умолчанию имеют значение undefined, что приводит к этой ошибке.

Другие вариации, такие как “number is not a function” возникают при попытке вызвать число, как будто оно является функцией.

Как исправить ошибку: убедитесь в корректности имени функции. Для этой ошибки, номер строки обычно указывает в правильное место.

Uncaught ReferenceError: Invalid left-hand side in assignment

Связанные ошибки: Uncaught exception: ReferenceError: Cannot assign to ‘functionCall()’, Uncaught exception: ReferenceError: Cannot assign to ‘this’

Вызвано попыткой присвоить значение тому, чему невозможно присвоить значение.

Наиболее частый пример этой ошибки — это условие в if:

if(doSomething() = 'somevalue')

В этом примере программист случайно использовал один знак равенства вместо двух. Выражение “left-hand side in assignment” относится к левой части знака равенства, а, как можно видеть в данном примере, левая часть содержит что-то, чему нельзя присвоить значение, что и приводит к ошибке.

Как исправить ошибку: убедитесь, что вы не пытаетесь присвоить значение результату функции или ключевому слову this.

Uncaught TypeError: Converting circular structure to JSON

Связанные ошибки: Uncaught exception: TypeError: JSON.stringify: Not an acyclic Object, TypeError: cyclic object value, Circular reference in value argument not supported

Всегда вызвано циклической ссылкой в объекте, которая потом передается в JSON.stringify.

var a = { };
var b = { a: a };
a.b = b;
JSON.stringify(a);

Так как a и b в примере выше имеют ссылки друг на друга, результирующий объект не может быть приведен к JSON.

Как исправить ошибку: удалите циклические ссылки, как в примере выше, из всех объектов, которые вы хотите сконвертировать в JSON.

Unexpected token ;

Связанные ошибки: Expected ), missing ) after argument list

Интерпретатор JavaScript что-то ожидал, но не обнаружил там этого. Обычно вызвано пропущенными фигурными, круглыми или квадратными скобками.

Токен в данной ошибке может быть разным — может быть написано “Unexpected token ]”, “Expected {” или что-то еще.

Как исправить ошибку: иногда номер строки не указывает на правильное местоположение, что затрудняет исправление ошибки.

Ошибка с [ ] { } ( ) обычно вызвано несовпадающей парой. Проверьте, все ли ваши скобки имеют закрывающую пару. В этом случае, номер строки обычно указывает на что-то другое, а не на проблемный символ.

Unexpected / связано с регулярными выражениями. Номер строки для данного случая обычно правильный.

Unexpected; обычно вызвано символом; внутри литерала объекта или массива, или списка аргументов вызова функции. Номер строки обычно также будет верным для данного случая.

Uncaught SyntaxError: Unexpected token ILLEGAL

Связанные ошибки: Unterminated String Literal, Invalid Line Terminator

В строковом литерале пропущена закрывающая кавычка.

Как исправить ошибку: убедитесь, что все строки имеют правильные закрывающие кавычки.

Uncaught TypeError: Cannot read property ‘foo’ of null, Uncaught TypeError: Cannot read property ‘foo’ of undefined

Связанные ошибки: TypeError: someVal is null, Unable to get property ‘foo’ of undefined or null reference

Попытка прочитать null или undefined так, как будто это объект. Например:

var someVal = null;
console.log(someVal.foo);

Как исправить ошибку: обычно вызвано опечатками. Проверьте, все ли переменные, использованные рядом со строкой, указывающей на ошибку, правильно названы.

Uncaught TypeError: Cannot set property ‘foo’ of null, Uncaught TypeError: Cannot set property ‘foo’ of undefined

Связанные ошибки: TypeError: someVal is undefined, Unable to set property ‘foo’ of undefined or null reference

Попытка записать null или undefined так, как будто это объект. Например:

var someVal = null;
someVal.foo = 1;

Как исправить ошибку: это тоже обычно вызвано ошибками. Проверьте имена переменных рядом со строкой, указывающей на ошибку.

Uncaught RangeError: Maximum call stack size exceeded

Связанные ошибки: Uncaught exception: RangeError: Maximum recursion depth exceeded, too much recursion, Stack overflow

Обычно вызвано неправильно программной логикой, что приводит к бесконечному вызову рекурсивной функции.

Как исправить ошибку: проверьте рекурсивные функции на ошибки, которые могут вынудить их делать рекурсивные вызовы вечно.

Uncaught URIError: URI malformed

Связанные ошибки: URIError: malformed URI sequence

Вызвано некорректным вызовом decodeURIComponent.

Как исправить ошибку: убедитесь, что вызовы decodeURIComponent на строке ошибки получают корректные входные данные.

XMLHttpRequest cannot load some/url. No ‘Access-Control-Allow-Origin’ header is present on the requested resource

Связанные ошибки: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at some/url

Эта проблема всегда связана с использованием XMLHttpRequest.

Как исправить ошибку: убедитесь в корректности запрашиваемого URL и в том, что он удовлетворяет same-origin policy. Хороший способ найти проблемный код — посмотреть на URL в сообщении ошибки и найти его в своём коде.

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

Связанные ошибки: InvalidStateError, DOMException code 11

Означает то, что код вызвал функцию, которую нельзя было вызывать в текущем состоянии. Обычно связано c XMLHttpRequest при попытке вызвать на нём функции до его готовности.

var xhr = new XMLHttpRequest();
xhr.setRequestHeader('Some-Header', 'val');

В данном случае вы получите ошибку потому, что функция setRequestHeader может быть вызвана только после вызова xhr.open.

Как исправить ошибку: посмотрите на код в строке, указывающей на ошибку, и убедитесь, что он вызывается в правильный момент или добавляет нужные вызовы до этого (как с xhr.open).

Заключение

JavaScript содержит в себе одни из самых бесполезных ошибок, которые я когда-либо видел, за исключением печально известной Expected T_PAAMAYIM_NEKUDOTAYIM в PHP. Большая ознакомленность с ошибками привносит больше ясности. Современные браузеры тоже помогают, так как больше не выдают абсолютно бесполезные ошибки, как это было раньше.

Какие самые непонятные ошибки вы встречали? Делитесь своими наблюдениями в комментариях.

P.S. Этот перевод можно улучшить, отправив PR здесь.

It looks like «$smth is not a function» is a very common problem with JavaScript, yet after looking through quite a few threads I still cannot understand what is causing it in my case.

I have a custom object, defined as:

function Scorm_API_12() {
var Initialized = false;

function LMSInitialize(param) {
    errorCode = "0";
    if (param == "") {
        if (!Initialized) {
            Initialized = true;
            errorCode = "0";
            return "true";
        } else {
            errorCode = "101";
        }
    } else {
        errorCode = "201";
    }
    return "false";
}

// some more functions, omitted.
}

var API = new Scorm_API_12();

Then in a different script I am trying to use this API in the following way:

var API = null;

function ScormProcessInitialize(){
    var result;

    API = getAPI();

    if (API == null){
        alert("ERROR - Could not establish a connection with the API.");
        return;
    }

    // and here the dreaded error pops up
    result = API.LMSInitialize("");

    // more code, omitted
    initialized = true;
}

The getAPI() stuff, looks like this:

var findAPITries = 0;

function findAPI(win)
{
   // Check to see if the window (win) contains the API
   // if the window (win) does not contain the API and
   // the window (win) has a parent window and the parent window
   // is not the same as the window (win)
   while ( (win.API == null) &&
           (win.parent != null) &&
           (win.parent != win) )
   {
      // increment the number of findAPITries
      findAPITries++;

      // Note: 7 is an arbitrary number, but should be more than sufficient
      if (findAPITries > 7)
      {
         alert("Error finding API -- too deeply nested.");
         return null;
      }

      // set the variable that represents the window being
      // being searched to be the parent of the current window
      // then search for the API again
      win = win.parent;
   }
   return win.API;
}

function getAPI()
{
   // start by looking for the API in the current window
   var theAPI = findAPI(window);

   // if the API is null (could not be found in the current window)
   // and the current window has an opener window
   if ( (theAPI == null) &&
        (window.opener != null) &&
        (typeof(window.opener) != "undefined") )
   {
      // try to find the API in the current window�s opener
      theAPI = findAPI(window.opener);
   }
   // if the API has not been found
   if (theAPI == null)
   {
      // Alert the user that the API Adapter could not be found
      alert("Unable to find an API adapter");
   }
   return theAPI;
}

Now, the API is probably found, because I do not get the «Unable to find…» message, the code proceeds to try to initialize it. But firebug tells me API.LMSInitialize is not a function, and if I try to debug it with alert(Object.getOwnPropertyNames(API));, it gives me a blank alert.

What am I missing?

TypeError: «x» is not a function

The JavaScript exception «is not a function» occurs when there was an attempt to call a value from a function, but the value is not actually a function.

Message

TypeError: Object doesn't support property or method {x} (Edge)
TypeError: "x" is not a function

Error type

TypeError

What went wrong?

It attempted to call a value from a function, but the value is not actually a function. Some code expects you to provide a function, but that didn’t happen.

Maybe there is a typo in the function name? Maybe the object you are calling the method on does not have this function? For example, JavaScript Objects have no map function, but the JavaScript Array object does.

There are many built-in functions in need of a (callback) function. You will have to provide a function in order to have these methods working properly:

  • When working with Array or TypedArray objects:
    • Array.prototype.every(), Array.prototype.some(), Array.prototype.forEach(), Array.prototype.map(), Array.prototype.filter(), Array.prototype.reduce(), Array.prototype.reduceRight(), Array.prototype.find()
  • When working with Map and Set objects:
    • Map.prototype.forEach() and Set.prototype.forEach()

Examples

A typo in the function name

In this case, which happens way too often, there is a typo in the method name:

let x = document.getElementByID('foo');

The correct function name is getElementById:

let x = document.getElementById('foo');

Function called on the wrong object

For certain methods, you have to provide a (callback) function and it will work on specific objects only. In this example, Array.prototype.map() is used, which will work with Array objects only.

let obj = {a: 13, b: 37, c: 42};

obj.map(function(num) {
  return num * 2;
});


Use an array instead:

let numbers = [1, 4, 9];

numbers.map(function(num) {
  return num * 2;
});


Function shares a name with a pre-existing property

Sometimes when making a class, you may have a property and a function with the same name. Upon calling the function, the compiler thinks that the function ceases to exist.

var Dog = function () {
 this.age = 11;
 this.color = "black";
 this.name = "Ralph";
 return this;
}

Dog.prototype.name = function(name) {
 this.name = name;
 return this;
}

var myNewDog = new Dog();
myNewDog.name("Cassidy"); 

Use a different property name instead:

var Dog = function () {
 this.age = 11;
 this.color = "black";
 this.dogName = "Ralph"; 
 return this;
}

Dog.prototype.name = function(name) {
 this.dogName = name;
 return this;
}

var myNewDog = new Dog();
myNewDog.name("Cassidy"); 

Using brackets for multiplication

In math, you can write 2 × (3 + 5) as 2*(3 + 5) or just 2(3 + 5).

Using the latter will throw an error:

const sixteen = 2(3 + 5);
alert('2 x (3 + 5) is ' + String(sixteen));

You can correct the code by adding a * operator:

const sixteen = 2 * (3 + 5);
alert('2 x (3 + 5) is ' + String(sixteen));

Import the exported module correctly

Ensure you are importing the module correctly.

An example helpers library (helpers.js)

let helpers = function () { };

helpers.groupBy = function (objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    var key = obj[property];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
  },
{});
}

export default helpers;

The correct import usage (App.js):

import helpers from './helpers'

See also

  • Functions

TypeError:»x» не является функцией

Исключение JavaScript «не является функцией» возникает,когда была попытка вызвать значение из функции,но на самом деле значение не является функцией.

Message

TypeError: "x" is not a function. (V8-based & Firefox & Safari)

Error type

Что пошло не так?

Она пыталась вызвать значение из функции,но на самом деле значение не является функцией.Какой-то код ожидает,что вы предоставите функцию,но этого не произошло.

Может, в названии функции опечатка? Может быть, объект, для которого вы вызываете метод, не имеет этой функции? Например, у Objects JavaScript нет функции map , но у объекта Array JavaScript есть.

Существует множество встроенных функций,нуждающихся в функции (обратного вызова).Чтобы эти методы работали должным образом,вам необходимо предоставить функцию:

  • При работе с объектами Array или TypedArray :
    • Array.prototype.every(), Array.prototype.some(), Array.prototype.forEach(), Array.prototype.map(), Array.prototype.filter(), Array.prototype.reduce(), Array.prototype.reduceRight(), Array.prototype.find()
  • При работе с объектами Map и Set :
    • Map.prototype.forEach() и Set.prototype.forEach()

Examples

Ошибка в названии функции

В этом случае,что случается слишком часто,в названии метода присутствует опечатка:

const x = document.getElementByID('foo');

Правильное имя функции — getElementById :

const x = document.getElementById('foo');

Функция вызвана не на том объекте

Для определенных методов вы должны предоставить функцию (обратного вызова), и она будет работать только с определенными объектами. В этом примере используется Array.prototype.map() , который работает только с объектами Array .

const obj = { a: 13, b: 37, c: 42 };

obj.map(function (num) {
  return num * 2;
});


Вместо этого используйте массив:

const numbers = [1, 4, 9];

numbers.map(function (num) {
  return num * 2;
});


Функция разделяет имя с ранее существовавшей собственностью

Иногда при создании класса может быть свойство и функция с тем же именем.При вызове функции компилятор думает,что функция перестает существовать.

function Dog() {
  this.age = 11;
  this.color = "black";
  this.name = "Ralph";
  return this;
}

Dog.prototype.name = function (name) {
  this.name = name;
  return this;
}

const myNewDog = new Dog();
myNewDog.name("Cassidy"); 

Вместо этого используйте другое имя свойства:

function Dog() {
  this.age = 11;
  this.color = "black";
  this.dogName = "Ralph"; 
  return this;
}

Dog.prototype.name = function (name) {
  this.dogName = name;
  return this;
}

const myNewDog = new Dog();
myNewDog.name("Cassidy"); 

Использование скобок для умножения

В математике 2 × (3+5)можно записать как 2*(3+5)или просто 2(3+5).

Использование последнего приведет к ошибке:

const sixteen = 2(3 + 5);
console.log(`2 x (3 + 5) is ${sixteen}`);

Вы можете исправить код, добавив оператор * :

const sixteen = 2 * (3 + 5);
console.log(`2 x (3 + 5) is ${sixteen}`);

Правильно импортируйте экспортированный модуль

Убедитесь,что вы правильно импортируете модуль.

Пример библиотеки помощников ( helpers.js )

const helpers = function () { };

helpers.groupBy = function (objectArray, property) {
  return objectArray.reduce((acc, obj) => {
    const key = obj[property];
    acc[key] ??= [];
    acc[key].push(obj);
    return acc;
  }, {});
}

export default helpers;

Правильное использование импорта ( App.js ):

import helpers from './helpers';

See also

  • Functions


JavaScript

  • RangeError:аргумент не является корректной кодовой точкой

    Исключение JavaScript «Недопустимая кодовая точка» возникает, когда значения NaN, отрицательные целые числа (-1), нецелые числа (5.4) или больше 0x10FFFF (1114111)

  • TypeError: «x» не является конструктором

    Исключение JavaScript «не является конструктором» возникает, когда была попытка использовать объектную переменную, но была попытка использовать объект или переменную

  • ReferenceError: «x» не определен

    Исключение JavaScript «переменная не определена» возникает, когда где-то есть несуществующая ссылка.

  • RangeError:точность вне досягаемости

    Исключение JavaScript «точность вне допустимого диапазона» возникает, когда число, выходящее за пределы 0 и 20 (или 21), было передано в toFixed toPrecision.

The JavaScript exception «is not a function» occurs when there was an attempt to call a value from a function, but the value is not actually a function.

Message

TypeError: Object doesn't support property or method {x} (Edge)
TypeError: "x" is not a function

Error type

TypeError

What went wrong?

It attempted to call a value from a function, but the value is not actually a function. Some code expects you to provide a function, but that didn’t happen.

Maybe there is a typo in the function name? Maybe the object you are calling the method on does not have this function? For example, JavaScript Objects have no map function, but the JavaScript Array object does.

There are many built-in functions in need of a (callback) function. You will have to provide a function in order to have these methods working properly:

  • When working with Array or TypedArray objects:
    • Array.prototype.every(), Array.prototype.some(), Array.prototype.forEach(), Array.prototype.map(), Array.prototype.filter(), Array.prototype.reduce(), Array.prototype.reduceRight(), Array.prototype.find()
  • When working with Map and Set objects:
    • Map.prototype.forEach() and Set.prototype.forEach()

Examples

A typo in the function name

In this case, which happens way too often, there is a typo in the method name:

let x = document.getElementByID('foo');
// TypeError: document.getElementByID is not a function

The correct function name is getElementById:

let x = document.getElementById('foo');

Function called on the wrong object

For certain methods, you have to provide a (callback) function and it will work on specific objects only. In this example, Array.prototype.map() is used, which will work with Array objects only.

let obj = {a: 13, b: 37, c: 42};

obj.map(function(num) {
  return num * 2;
});

// TypeError: obj.map is not a function

Use an array instead:

let numbers = [1, 4, 9];

numbers.map(function(num) {
  return num * 2;
});

// Array [2, 8, 18]

Function shares a name with a pre-existing property

Sometimes when making a class, you may have a property and a function with the same name. Upon calling the function, the compiler thinks that the function ceases to exist.

var Dog = function () {
 this.age = 11;
 this.color = "black";
 this.name = "Ralph";
 return this;
}

Dog.prototype.name = function(name) {
 this.name = name;
 return this;
}


var myNewDog = new Dog();
myNewDog.name("Cassidy"); //Uncaught TypeError: myNewDog.name is not a function

Use a different property name instead:

var Dog = function () {
 this.age = 11;
 this.color = "black";
 this.dogName = "Ralph"; //Using this.dogName instead of .name
 return this;
}

Dog.prototype.name = function(name) {
 this.dogName = name;
 return this;
}


var myNewDog = new Dog();
myNewDog.name("Cassidy"); //Dog { age: 11, color: 'black', dogName: 'Cassidy' }

Using brackets for multiplication

In math, you can write 2 × (3 + 5) as 2*(3 + 5) or just 2(3 + 5).

Using the latter will throw an error:

const sixteen = 2(3 + 5);
alert('2 x (3 + 5) is ' + String(sixteen));
//Uncaught TypeError: 2 is not a function

You can correct the code by adding a * operator:

const sixteen = 2 * (3 + 5);
alert('2 x (3 + 5) is ' + String(sixteen));
//2 x (3 + 5) is 16

Import the exported module correctly

Ensure you are importing the module correctly.

An example helpers library (helpers.js)

let helpers = function () { };

helpers.groupBy = function (objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    var key = obj[property];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
  },
{});
}

export default helpers;

The correct import usage (App.js):

import helpers from './helpers'

See also

  • Functions

Понравилась статья? Поделить с друзьями:
  • Is mf02 5 ошибка gta v
  • Is mf01 ошибка доступа к файлу установки
  • Is lulu is in the garden где ошибка
  • Is fc05 файл поврежден код ошибки
  • Is done dll произошла ошибка при распаковке