TypeError: Cannot read property 'then' of undefined

  • I am having an error with Web3. After going through all possibilities I decided to post a question hoping for someone with a solution.

    The error I keep getting is:

    TypeError: Cannot read property 'then' of undefined

    web3.eth.getAccounts().then(accounts => {
       web3.eth.getBalance(accounts[0]).then(balance => {
          console.log(balance);
        }
    }
    



    Note: this exact same code is running fine on two other servers. I do have the exact same versions of Truffle, React..etc as the other two.

    Any solutions will be appreciated! Thanks in advance.

    what is the web3 version you use?

    Things related to `.then` have changed with version, you should specify your web3 version in question.

    You need at least web3 v1.0 because it has support for promises, for version v0.20 it only supported callbacks, you have to use a third party library like bluebird to promisify functions.

    did you solve this problem?

  • have you tried to add a catch in order to output the stacktrace of your error ?

    Just add at the end of your promise chain : then(account => {...}).catch( err => { console.log(err); }

    You'll then be able to see in the console the stacktrace of the error and distinguish if it is accounts or accounts[0] which is undefined.

    If it is accounts[0], ensure your web3 instance is connected. If is is the whole accounts object, ensure you use Web3.js v1.x.x and not v.0.2.x

    unfortunately somehow my error was thrown before this catch was in effect, possibly because I used jQuery. ```jQuery.Deferred exception: Cannot read property 'then' of undefined TypeError: Cannot read property 'then' of undefined```

  • Try wrapping it in an asynchronous function:

    private async deployContract(): Promise<string> {
      web3.eth.getAccounts().then...
      ...
      return Promise.resolve('Check done');
    }
    

License under CC-BY-SA with attribution


Content dated before 7/24/2021 11:53 AM