繁体   English   中英

未处理的运行时错误 => TypeError:无法读取未定义的属性(读取“setState”)

[英]Unhandled Runtime Error => TypeError: Cannot read properties of undefined (reading 'setState')

当我尝试连接到 Metamask 上的 Rinkeby 测试网络时,我遇到了这个运行时错误,它说 setState 未定义。 我曾尝试使用构造函数道具进行绑定,但这不起作用。 我不知道该怎么办。 这是我的代码:

import React, { Component } from 'react'
import { Button, Form, Input, Grid, Message } from 'semantic-ui-react'
import Layout from '../../components/Layout'
import factory from '../../ethereum/factory'
import web3 from '../../ethereum/web3'
import { Router } from '../../routes'

class New extends React.Component {


constructor(props) {
super(props);
this.state = {
    minimumContribution: '',
    errorMessage: '',
    loading: false
  }
this.onSubmit = this.onSubmit.bind(this);
  }

onSubmit = async event => {
event.preventDefault()
const accounts = await web3.eth.getAccounts()
this.setState({ loading: true, errorMessage: '' })

try {
  await factory.methods.createCampaign(this.state.minimumContribution).send({
    from: accounts[0]
  });

  Router.pushRoute('/')
} catch (error) {
  this.setState({ errorMessage: error.message })
}
this.setState({ loading: false })
}

render() {
const { errorMessage, loading } = this.state
return (
  <Layout>
    <Grid centered columns={2}>
      <Grid.Column>
        <h3>Create a Campaign.</h3>
        <Form onSubmit={this.onSubmit} error={!!errorMessage}>
          <Form.Field>
            <lable>Minimum Contribution </lable>
            <Input
              label="WEI"
              labelPosition="right"
              value={this.state.minimumContribution}
              onChange={event=>this.setState({minimumContribution:event.target.value})}
            />
          </Form.Field>
          <Message error header="Oops!" content={errorMessage}/>
          <Button loading={loading} primary>Create</Button>
        </Form>
      </Grid.Column>
    </Grid>
  </Layout>
    )
   }
  }

  export default New

如果它确实有帮助,我正在学习关于 Udemy 的以太坊课程(以太坊和 Solidity:完整的开发人员指南)。 错误发生在第 190 课。

您应该使用async onSubmit (event) {而不是onSubmit = async event => {

前者声明一个方法,而后者用箭头 function 初始化 class 属性。 箭头函数没有自己的this (不,绑定不会改变它),因此将使用周围范围的this ,这将是全局 scope ( class块不是 Z31A1FD140BE4BEF2D511E181EC9A1 因为它不能包含本身代码),并且全局范围的thisundefined ,因此,您的代码当前在访问this.setState崩溃。

看起来“this”上下文正在丢失。

使用箭头 function 添加新方法

handleChange = event => this.setState({minimumContribution:event.target.value})

参考 onChange 中的 function

onChange={this.handleChange}

删除this.onSubmit = this.onSubmit.bind(this); 如果要使用 class 属性,请从构造函数中获取。 有关更多信息,请参阅如何使用箭头函数(公共 class 字段)作为 class 方法?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM