Skip to content

Class instance properties do not work in async arrow functions #24068

Closed
@rrgomide

Description

@rrgomide

🐛 Bug Report

Hi, I've been trying to upgrade a project created with React Native 0.51.0 and, starting from 0.57, class instance properties are not working correctly anymore in async arrow functions (in my opinion). They're correctly interpreted in async functions (not arrow functions) as you'll see in the code examples. In my old project everything works as expected. My guess is that it's a problem with babel config, since it has been upgraded to version 7 and at react-native 0.51 it was version 6.

To Reproduce

Create any project from react-native 0.57 or later versions. I haven't tried with Expo.

Expected Behavior

this.number should be read correctly on componentDidMount arrow function.

Code Example

export default class App extends Component {
  constructor() {
    super();

    //Instance property
    this.number = 1;
  }

  //async arrow function
  componentDidMount = async () => {
    console.log(this.number); //it shows undefined and "this" is the global one
    this.otherMethod();
  };

  //"normal" async function
  async otherMethod() {
    console.log(this.number); //it shows 1 and expected value for "this"
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>Welcome to React Native!</Text>
        <Text style={styles.instructions}>To get started, edit App.js</Text>
        <Text style={styles.instructions}>{instructions}</Text>
      </View>
    );
  }
}

I put the following similar code in Babel's "try out" feature and tested on Chrome. Everything worked as expected. That's why I created the issue here, on react-native project:

class Test {
  constructor() {
    this.number =1;    
  }
  
  sum = async() => {
    this.number++;
    console.log(this.number);
  }  
  
  test = async() => {
    fetch('http://google.com').then((res) => {
      this.number++;
      console.log(this.number);
    })
    .catch((error) => {
      this.number++;
      console.log(this.number);
    })
  }
}

const test = new Test();
test.sum();

Environment

React Native Environment Info:
System:
OS: Windows 7
CPU: (8) x64 Intel(R) Core(TM) i7-4770 CPU @ 3.40GHz
Memory: 173.64 MB / 7.91 GB
Binaries:
Node: 10.15.1 - C:\nodejs\node.EXE
Yarn: 1.13.0 - C:\Program Files (x86)\Yarn\bin\yarn.CMD
npm: 6.7.0 - C:\nodejs\npm.CMD

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions