Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React 'this' is undefined in Chrome developer tools [duplicate]

When I inspect my React code in the Chrome developer tools 'Source' tab, and I hover over the 'this.props' or even 'this' keyword / add it to watches, it shows up as undefined. Even though the code referred to executes successfully. Very annoying.... is this is bug? Is there a workaround for this?

enter image description here

like image 295
Marc Avatar asked Feb 15 '19 15:02

Marc


People also ask

Why does Chrome console say undefined?

If the expression doesn't return a value, the console will report undefined — this doesn't mean anything is wrong, it's just letting you know that the previous expression didn't return a result.

How do I enable react tools in Chrome?

The quickest way to open React Devtools is to right click your page and select inspect. If you've used Chrome or Firefox's developer tools, this view should look a little familiar to you.

What is DevTool?

Developer tools (or "development tools" or short "DevTools") are programs that allow a developer to create, test and debug software. Current browsers provide integrated developer tools, which allow to inspect a website.


2 Answers

It's undefined because you're inside an arrow function and by definition an arrow function doesn't own a context but it inherits the enclosing one.

If you check the menu on the right handside and scroll down to the current scope you will find the closure chain of that function (one of which in your case will be the component class) that has the this inherited by your function.

e.g.

enter image description here

An arrow function does not have its own this. The this value of the enclosing lexical scope is used;

Arrow functions doc

like image 169
Karim Avatar answered Sep 16 '22 17:09

Karim


Due to how lexical this is treated by Babel in arrow functions, it cannot be this inside an arrow. Temporary variables like _this, _this2, etc. are used to imitate lexical this in ES5.

Transpiled code looks like:

var _this = this;
...
.then(function () {
  ...
  _this.setState(...);
});

Even though it appears like original ES6 source in debugger because of sourcemaps, it's ES5 that is evaluated. So it's _this local variable that needs to be debugged.

like image 24
Estus Flask Avatar answered Sep 19 '22 17:09

Estus Flask