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

泪湿孤枕 提交于 2019-11-26 21:57:01

问题


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?


回答1:


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.




回答2:


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 right menu 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.

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

Arrow functions doc



来源:https://stackoverflow.com/questions/54712662/react-this-is-undefined-in-chrome-developer-tools

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!