JavaScript error: “is not a function”

前端 未结 3 1205
太阳男子
太阳男子 2020-12-03 13:18

It looks like \"$smth is not a function\" is a very common problem with JavaScript, yet after looking through quite a few threads I still cannot understand what is causing i

3条回答
  •  情歌与酒
    2020-12-03 14:16

    I also hit this error. In my case the root cause was async related (during a codebase refactor): An asynchronous function that builds the object to which the "not a function" function belongs was not awaited, and the subsequent attempt to invoke the function throws the error, example below:

    const car = carFactory.getCar();
    car.drive() //throws TypeError: drive is not a function
    

    The fix was:

    const car = await carFactory.getCar();
    car.drive()
    

    Posting this incase it helps anyone else facing this error.

提交回复
热议问题