Value of “this” is incorrect when debugging Babel transpiled React with Chrome Devtools

泄露秘密 提交于 2019-11-26 14:47:56

问题


I have a React application that is transpiled with Babel using the following .babelrc configuration

{
  "presets": [
    "es2015",
    "stage-1",
    "react"
  ],
  "plugins": [
    "transform-decorators-legacy"
  ]
}

The application transpiles and runs fine. However, when I debug event handlers (purposely written as arrow functions), the Chrome debugger displays the value of "this" as null. Here is a sample event handler

handleNext = (event) => {
    event.preventDefault();
    this.gotoPage(this.state.page + 1);
}

If I set a breakpoint on the first line of the event handler, the debugger displays the value of "this" as null but displays "_this" as the correct value for "this". As I said, the code runs clean, but debugging is frustrating since I cannot simply hover on fields in the code to see their value. I can work around the debugging issue if I bind "this" to my event handler, but I should not have to do that extra step. All of this worked fine in Babel5 and has only been an issue since we switched to Babel6.

I am using webpack to bundle the code and create the sourcemaps. Here is an excerpt from my webpack.config.js for sourcemaps configuration

plugins: [
new webpack.SourceMapDevToolPlugin({
  filename: '[name].js.map',
  include: ['app.js'],
  columns: false
})
],

回答1:


Unfortunately this is a fact of life when using the debugger in Babelified code with Chrome. To implement arrow functions with the ECMAScript spec behavior, the this keyword needs to be transformed into a different name, and there's currently no way to tell Chrome what do to for debugging. Firefox's developer tools have a bunch of extra logic to address issues like this, so it may work properly if you're using Firefox and enable to "Map Scopes" checkbox, but it can also be slower because it isn't trivial.

One option would be to try to use the spec option of the arrow function transformation, which should make this behave better for debugging, but may not work in all cases.

"plugins": [
    ["transform-es2015-arrow-functions", {spec: true}]
]


来源:https://stackoverflow.com/questions/36638663/value-of-this-is-incorrect-when-debugging-babel-transpiled-react-with-chrome-d

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