2

this is undefined in console "this" is undefined in devtool console while it is clearly not undefined. Must be a bug in devtools?

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Sathees
  • 119
  • 6
  • 2
    yes, more os less... I don't know how to explain exactly... The problem is that the code you are "inspecting" is actually ECMAScript 5 but the code you are "seeing" is ES6. When you type `this` in the console, the browser tries to show the `this` variable, but in the souce-code there is no `this` variable, the transpiler usually uses `_this`... Instead of inspecting `this` try `_this` and you will see the correct value – Fabio Oct 06 '16 at 19:07
  • Thanks, You are correct. The only difference is that in my case it looks like it is _this2 – Sathees Oct 06 '16 at 19:11
  • 1
    Yeah, it depends on several things... Take a look at the transpiled code (ES5) to see the real names of the variables – Fabio Oct 06 '16 at 19:13
  • 1
    Try selecting `this` (doubleclick it), then rightclick and choose `Evaluate in console`. Maybe it's smart enough. – wOxxOm Oct 06 '16 at 19:22
  • Possible duplicate of [Value of "this" is incorrect when debugging Babel transpiled React with Chrome Devtools](https://stackoverflow.com/questions/36638663/value-of-this-is-incorrect-when-debugging-babel-transpiled-react-with-chrome-d) – Bergi Aug 26 '19 at 21:24

1 Answers1

1

As you are inspecting ES6/ES2015+ code (thanks to source-maps) and not the actual code which is in less readable ES5-transpiled code, the this property is not the same as what you see in the source code.

To access this, try evaluating _this, _this1, _this2 and so forth in the console to find the context you are looking for.

const loaded = () => {
  this.setState({ loading: false });
};

// will be compiled/transpiled to

var _this = this;
var loaded = function loaded() {
  _this.setState({ loading: false });
};

Reference: https://www.sitepoint.com/bind-javascripts-this-keyword-react/

William Bernting
  • 561
  • 4
  • 15