Error handling response typeerror self processresponse is not a function

Getting this error in the Devtool(Console). Error handling response: TypeError: self.processResponse is not a function

Had the same issue running a site internally. Seems like that extension needs to be updated.

Error handling response: TypeError: self.processResponse is not a function
at chrome-extension://cmkdbmfndkfgebldhnkbfhlneefdaaip/js/notification.js:154:10

and this references index.html line 1 as the source of the error pointing back to the notification.js file called by that extension.

and this was on a bare html file:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Javascript Debug Challenge</title>
    
</head>
<body>
    <!-- <script src="/part-1.js" type="text/javascript"></script>-->
    <!-- <script src="/part-2.js" type="text/javascript"></script>-->
    <!-- <script src="/part-3.js" type="text/javascript"></script>-->
    <!-- <script src="/part-4.js" type="text/javascript"></script>-->
    <script src="/part-5.js" type="text/javascript"></script>
</body>
</html>

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: "x" is not a function. (V8-based & Firefox & Safari)

Error type

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:

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

The correct function name is getElementById:

const 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.

const 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:

const numbers = [1, 4, 9];

numbers.map(function (num) {
  return num * 2;
}); // [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.

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"); //Uncaught TypeError: myNewDog.name is not a function

Use a different property name instead:

function Dog() {
  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;
};

const 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);
console.log(`2 x (3 + 5) is ${sixteen}`);
// Uncaught TypeError: 2 is not a function

You can correct the code by adding a * operator:

const sixteen = 2 * (3 + 5);
console.log(`2 x (3 + 5) is ${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)

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;

The correct import usage (App.js):

import helpers from "./helpers";

See also

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

Просмотры 389K

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 здесь.

The Javascript error TypeError: "x" is not a function occurs when there is an attempt to call a function on a value or object, which is not actually a function.

Error message:

TypeError: "x" is not a function

Error Type:

TypeError

What Causes TypeError: «x» is not a function

A TypeError: "x" is not a function in Javascript generally occurs in one of the following scenarios:

  • A typographical error in a function call.
  • Missing script library.
  • When a function is called on a property that is not actually a function.
  • A TypeError: "x" is not a function occurs when a function is called on an object that does not contain the called function.
  • When calling a built-in function that expects a callback function argument, which does not exist.
  • When the called function is within a scope that is not accessible

TypeError: «x» is not a function Examples

1. Typo

A typical scenario for the TypeError: "x" is not a function to occur is when there is a typo in the called function name:

var elem = document.getElementByID('ID');

Running the above code leads to the following Javascript error:

TypeError: document.getElementByID is not a function

The correct function name is getElementById():

var elem = document.getElementById('ID');

2. Object Does Not Contain Function

Another common cause for the TypeError: "x" is not a function is when a function is called an object that does not actually contain the function:

var foo = {
   bar: function() {
      console.log("bar called");
   }
};
foo.baz();

In the above example, the foo object contains a function bar(). However, the above code attempts to call the function baz(), which foo does not contain. Running the above code leads to the following Uncaught TypeError: "x" is not a function:

Uncaught TypeError: foo.baz is not a function

If the Javascript code is modified to call the correct function bar():

var foo = {
   bar: function() {
      console.log("bar called");
   }
};    
foo.bar();

The correct output is produced:

bar called

How to Fix Javascript TypeError: «x» is not a function

The TypeError: "x" is not a function can be fixed using the following suggestions:

  • Paying attention to detail in code and minimizing typos.
  • Importing the correct and relevant script libraries used in code.
  • Making sure the called property of an object is actually a function.
  • Making sure objects contain the called function to avoid TypeError: "x" is not a function.
  • Making sure functions passed in as callbacks do exist.
  • Making sure called functions are within the correct and accessible scope.

Track, Analyze and Manage Errors With Rollbar

Rollbar in action

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Javascript errors easier than ever. Sign Up Today!

Получение этой ошибки в Devtool (консоли).

Ответ обработки ошибок: TypeError: self.processResponse не является функцией

3 ответа

Лучший ответ

Проблема решена. Похоже, эта проблема возникает из-за расширения Chrome (Что работает).

enter image description here


17

Anup Dhal
15 Июл 2022 в 21:21

Была такая же проблема с запуском сайта внутри. Похоже, это расширение нужно обновить.

Ответ при обработке ошибки: TypeError: self.processResponse не является функцией chrome-extension: //cmkdbmfndkfgebldhnkbfhlneefdaaip/js/notification.js: 154: 10

И это ссылается на строку 1 index.html как на источник ошибки, указывающий на файл уведомления.js, вызываемый этим расширением.

И это было в голом html-файле:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Javascript Debug Challenge</title>
    
</head>
<body>
    <!-- <script src="/part-1.js" type="text/javascript"></script>-->
    <!-- <script src="/part-2.js" type="text/javascript"></script>-->
    <!-- <script src="/part-3.js" type="text/javascript"></script>-->
    <!-- <script src="/part-4.js" type="text/javascript"></script>-->
    <script src="/part-5.js" type="text/javascript"></script>
</body>
</html>


0

Greg Perry
22 Авг 2022 в 20:27

Просто отключив расширение Chrome WhatRuns, я решил проблему.


0

ilir prevazi
21 Окт 2022 в 15:37

Получение этой ошибки в Devtool (консоли).

Ответ на обработку ошибок: TypeError: self.processResponse не является функцией

5 причин выбрать React Native для вашего следующего мобильного приложения

Кто такой АУДИТОР смарт-контракта?

REACT и NEXT JS вместе с Tailwind CSS

REACT и NEXT JS вместе с Tailwind CSS

Наличие собственного или персонального сайта необходимо в современном мире, а сочетание React и Next JS позволяет разработчику сделать это за меньшее…

[JS за 1 час] - 9. Асинхронный

[JS за 1 час] — 9. Асинхронный

JavaScript является однопоточным, то есть он может обрабатывать только одну задачу за раз. Для обработки длительных задач, таких как сетевые запросы,…

Подъем в javascript

Подъем в javascript

Hoisting — это поведение в JavaScript, при котором переменные и объявления функций автоматически «перемещаются» в верхнюю часть соответствующих…

Как использовать API парсинга квитанций с помощью JavaScript за 5 минут?


Ответы
1

Ответ принят как подходящий

Проблема решена: Эта проблема возникает из-за расширения Chrome (Что работает).

Была та же проблема, и удаление расширения «Что работает» решило ее.


— 1c0DevPi

12.08.2022 13:19

Другие вопросы по теме

frontendmasters / web-workers
Goto Github
PK

View Code? Open in Web Editor
NEW

13.0
4.0
27.0
5 KB

Code for the Web Workers section of the Service Workers course by Kyle Simpson

JavaScript 69.60%

CSS 17.42%

HTML 12.99%

web-workers’s Introduction

Service Workers & Offline Course by Kyle Simpson

Code for the Web Workers section of the Service Workers and Offline course by Kyle Simpson.

Starter Exercise Files

To get started, download the Starter Files (ZIP)

Don’t forget to npm install the necessary modules.

web-workers’s People

web-workers’s Issues

Error handling response: TypeError: self.processResponse is not a function

Hi,
While using the sample code on Web worker sample I got the following error: «Error handling response: TypeError: self.processResponse is not a function
at chrome-extension://cmkdbmfndkfgebldhnkbfhlneefdaaip/js/notification.js:154:10
thanks.

This prevents me from going forward.
Thanks

Recommend Projects

  • React photo

    React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo

    Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo

    Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo

    TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo

    Django

    The Web framework for perfectionists with deadlines.

  • Laravel photo

    Laravel

    A PHP framework for web artisans

  • D3 photo

    D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Visualization

    Some thing interesting about visualization, use data art

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo

    Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo

    Microsoft

    Open source projects and samples from Microsoft.

  • Google photo

    Google

    Google ❤️ Open Source for everyone.

  • Alibaba photo

    Alibaba

    Alibaba Open Source for everyone

  • D3 photo

    D3

    Data-Driven Documents codes.

  • Tencent photo

    Tencent

    China tencent open source team.

Понравилась статья? Поделить с друзьями:
  • Error handling response typeerror cannot read properties of undefined reading direction
  • Error handling nestjs
  • Error handling jsf
  • Error handling in node js
  • Error handling file saving did the server never start