I am running a next.js app, with a file "temp.js" in the /pages directory. My code (temp.js) is as follows:
import React from 'react';
import {Button} from '@mui/material';
class SomeClass extends React.Component{
state={
someState: false
}
handleClick = async(someValue) => {
this.setState({ someState: true });
// await someAsyncFunction(someValue);
console.log(someValue);
}
render(){
return(
<Button onClick={()=>this.handleClick(12)}>
Click me.!
</Button>
)
}
}
export default SomeClass;
Stack Snippet (using button instead of MUI Button, but that doesn't matter):
<div id="root"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.development.js"></script>
<script type="text/babel" data-presets="es2017,react,stage-3">
class SomeClass extends React.Component{
state={
someState: false
}
handleClick = async(someValue) => {
this.setState({ someState: true });
// await someAsyncFunction(someValue);
console.log(someValue);
}
render(){
return(
<button onClick={()=>this.handleClick(12)}>
Click me.!
</button>
)
}
}
ReactDOM.render(<SomeClass />, document.getElementById("root"));
</script>
<script src="https://unpkg.com/[email protected]/runtime.js"></script>
<script src="https://unpkg.com/@babel/[email protected]/babel.min.js"></script>
This gives the following error:
Unhandled Runtime Error
TypeError: Cannot read properties of undefined (reading 'setState')
7 | }
8 | handleClick = async(someValue) => {
> 9 | this.setState({ someState: true });
| ^
10 | console.log(someValue);
11 | }
12 | render(){
This function would work fine if the 'someValue' was not required. Need help. Please ask for any clarifications.
.. Other than not handling rejections (see below), that code looks like it should run.asyncfunction from a non-asyncfunction, always be sure to handle promise rejections. Otherwise, they won't be handled by anything.handleClickis an arrow function in a context where it will close overthiscorrectly, sothiswill not be undefined. The code you're running that has this error must be different from the above. Please update your question with a minimal reproducible example demonstrating the problem, ideally a runnable one using Stack Snippets (the[<>]toolbar button). Stack Snippets support React, including JSX; here's how to do one.handleClickthrows an error then adding logic that deals with the return value ofhandleClickisn't going to help.buttoninstead of MUI'sButton, which is not going to affect what you've described). As you can see, it works just fine. Please edit the code in thescript type="text/babel"tag in the snippet with your real code causing the error.