react-hot-loader/babel creates invalid code with async arrow functions

Created on 20 Sep 2016  路  8Comments  路  Source: gaearon/react-hot-loader

On a class (that is _not_ a React component), there is a method defined through an arrow function:

show = async (id, type) => {
  const { data } = await apiRequest(/*...*/)

Without the es2015 preset (only stage-2, react, and react-hot-loader/babel), this gets transformed to:

_createClass(ClassName, [{
    key: '__show__REACT_HOT_LOADER__',
    value: function __show__REACT_HOT_LOADER__(id, type) {
      var { data } = await apiRequest(/*...*/);

This creates an await statement not inside an async function, which is invalid syntax.

This happens with beta.4, but rolling back to (the previously working?) beta.3 does not seem to help.

bug

Most helpful comment

webpack 2, 3.0.0-beta.5 'this' context lost in async arrow functions;

name = async () => {
this is undefined;
}

All 8 comments

Correction: this happens even with the es2015 preset, as the plugin run before presets, and it deletes the async keyword that the transform-async-to-generator relies on.

JUST SPENT 6 HOURS TRYING TO SOLVE THIS

馃槶

(not yelling at anyone just expressing relief that i finally located the issue)

馃槥 That's no good! Sorry @jquense!

It makes sense that this would happen in beta.4, since we added the class properties transform, and the plugin is not yet aware of async functions.

I think it should be a straight forward fix, test case:

actual

class Foo {
  bar = async (a, b) => {
    return await a(b);
  };
}

expected

var _this = this;

class Foo {
  bar = async (...params) => await _this.__bar__REACT_HOT_LOADER__(...params);

  async __bar__REACT_HOT_LOADER__(a, b) {
    return await a(b);
  }

}
;

(function () {
  if (typeof __REACT_HOT_LOADER__ === 'undefined') {
    return;
  }

  __REACT_HOT_LOADER__.register(Foo, "Foo", __FILENAME__);
})();

;

@jquense Awesome, thanks!

Out in 3.0.0-beta.5.

webpack 2, 3.0.0-beta.5 'this' context lost in async arrow functions;

name = async () => {
this is undefined;
}

seems like that would be true for any class prop function? I wonder why...

Was this page helpful?
0 / 5 - 0 ratings