You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React项目中Promise.then()内函数及setState提示undefined问题求助

问题分析与解决方案

你猜的没错,这确实是作用域/this指向的问题!咱们一步步拆解问题和对应的解决办法:

1. 直接修正当前代码的错误

你现在写的 .then(() => this.getAthleteData().bind(this)) 犯了两个小错误:

  • 你先调用了 getAthleteData(),再去绑定this,这时候函数已经执行完了,bind完全没起到作用
  • 箭头函数本身已经帮你捕获了外层的this(也就是组件实例),根本不需要额外bind

直接改成下面这样就行:

deleteWorkout(id, e) {
  e.preventDefault();
  fire.database().ref("athlete")
    .child(id).remove()
    // 箭头函数保留了组件的this,直接调用方法即可
    .then(() => this.getAthleteData())
    .catch(e => console.log(e));
}

2. 预防后续的this绑定问题

如果调整后还是报错,那大概率是deleteWorkout或者getAthleteData本身的this没绑定到组件实例。给你三种常用的绑定方式:

方式一:构造函数内手动绑定

constructor(props) {
  super(props);
  // 把两个方法的this绑定到组件实例
  this.deleteWorkout = this.deleteWorkout.bind(this);
  this.getAthleteData = this.getAthleteData.bind(this);
}

方式二:用箭头函数定义组件方法

这种方式会自动把this绑定到组件实例,不用额外处理:

// 箭头函数定义deleteWorkout
deleteWorkout = (id, e) => {
  e.preventDefault();
  fire.database().ref("athlete")
    .child(id).remove()
    .then(() => this.getAthleteData())
    .catch(e => console.log(e));
}

// 同样用箭头函数定义getAthleteData
getAthleteData = () => {
  // 你的数据获取逻辑
  fire.database().ref("athlete").once('value').then(snapshot => {
    this.setState({ athletes: snapshot.val() });
  });
}

方式三:JSX中调用时用箭头函数

如果是在JSX里绑定点击事件,也可以直接用箭头函数传递:

<button onClick={(e) => this.deleteWorkout(id, e)}>删除记录</button>

3. 额外优化:利用Firebase实时监听省掉手动刷新

其实Firebase支持实时数据监听,你完全不用手动调用getAthleteData刷新。只要在组件挂载时设置一次监听,数据(包括删除后)变化时会自动更新组件:

componentDidMount() {
  // 监听athlete节点的实时变化
  this.athleteRef = fire.database().ref("athlete");
  this.athleteRef.on('value', snapshot => {
    this.setState({ athletes: snapshot.val() });
  });
}

componentWillUnmount() {
  // 组件卸载时取消监听,避免内存泄漏
  this.athleteRef.off();
}

这样删除操作完成后,Firebase会自动通知数据变化,组件视图会自动更新,连手动调用刷新的步骤都省了~

内容的提问来源于stack exchange,提问作者UnknownFrequency

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:15:54