2

Language: React/JavaScript ES6

Bundling Tool: Webpack(babel-loader 6.0.0)

Other Libs Involved : Leaflet

Problem:

With the function below the context this is bound to the component as I need.

Before:

componentDidMount: function() {

     map.on('draw:created', function(e){
        this.setState({someProp:propUpdate});
        featureGroup.addLayer(e.layer);
     }.bind(this));

    }

But when I switched it over to using the arrow function I expected an equivalent binding, but this changed to a leaflet Class o.Class.extend.e - leaving this.setState undefined.

After:

componentDidMount: function() {

    map.on('draw:created', (e) => {
        this.setState({someProp:propUpdate});
        featureGroup.addLayer(e.layer);
    });

}

Question: Why is using the arrow function not the equivalent of binding this in my case?

10
  • 1
    Refer stackoverflow.com/questions/38127635/…
    – Rayon
    Commented Jul 2, 2016 at 1:37
  • @Rayon that example of arrow functions in a forEach loop doesn't give any clues why my async callback is losing binding scope. Are you suggesting "lexical binding" is different from es5 binding? Commented Jul 2, 2016 at 1:51
  • 3
    Seems like a bug in your environment / transpiler. Although Babel should work fine. The code itself looks fine. I doubt we can help much if we cannot reproduce the issue. Commented Jul 2, 2016 at 2:04
  • 1
    So far I think @FelixKling is probably right. "react": "^0.14.0", "webpack": "^1.12.1", "babel-core": "^6.6.4", "babel-loader": "^6.2.4", "babel-polyfill": "^6.9.1", "babel-preset-es2015": "^6.6.0", "babel-preset-react": "^6.5.0", "babel-preset-stage-0": "^6.5.0" Commented Jul 2, 2016 at 2:08
  • 1
    Try upgrading to the latest version of babel. Commented Jul 2, 2016 at 2:09

1 Answer 1

1

Had the same issue. Turns out the Babel-loader (in my case using the preset '@babel/preset-env') does not bind the arrow function to this as one would expect.

Using this plugin in my webpack config added the correct binding

plugins: [
  ['@babel/plugin-transform-arrow-functions', { 'spec': true }]
]

Not the answer you're looking for? Browse other questions tagged or ask your own question.