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

React箭头函数内嵌套函数this未定义,如何调用setState?

解决箭头函数内部嵌套函数中调用setState的问题

这个问题我之前也碰到过,本质是普通函数和箭头函数的this绑定规则差异导致的:你外部的showDeleteConfirm是箭头函数,它的this继承自组件实例,但onOk是一个普通函数,调用时它的this会绑定到调用它的上下文(这里变成了undefined),所以拿不到组件的this来调用setState。

给你几个可行的解决方案:

方案一:把onOk改成箭头函数

箭头函数不会绑定自己的this,它会继承外部作用域的this,这样就能直接拿到组件实例的this了:

showDeleteConfirm = commentId => {
  const { deleteComment } = this.props;
  const { comments } = this.state; 
  confirm({
    title: 'Are you sure delete this?',
    okText: 'Yes',
    okType: 'danger',
    cancelText: 'No',
    onOk: () => { // 改用箭头函数定义onOk
      deleteComment(commentId);
      const targetPosition = _.findIndex(comments, item => item._id === commentId);
      if (targetPosition !== -1) {
        // 现在可以正常调用this.setState更新状态
        this.setState(prevState => ({
          comments: [
            ...prevState.comments.slice(0, targetPosition),
            ...prevState.comments.slice(targetPosition + 1)
          ]
        }));
      }
    }
  });
}

方案二:提前保存外部this的引用

在外部把组件的this存到一个变量里(比如that、self),然后在onOk里用这个变量替代this:

showDeleteConfirm = commentId => {
  const { deleteComment } = this.props;
  const { comments } = this.state; 
  const that = this; // 保存组件实例的this
  confirm({
    title: 'Are you sure delete this?',
    okText: 'Yes',
    okType: 'danger',
    cancelText: 'No',
    onOk() { 
      deleteComment(commentId);
      const targetPosition = _.findIndex(comments, item => item._id === commentId);
      if (targetPosition !== -1) {
        // 使用that来调用setState
        that.setState(prevState => ({
          comments: [
            ...prevState.comments.slice(0, targetPosition),
            ...prevState.comments.slice(targetPosition + 1)
          ]
        }));
      }
    }
  });
}

方案三:用bind绑定this到onOk函数

通过bind方法强制把onOk函数的this绑定到组件实例,这样调用时this就指向组件了:

showDeleteConfirm = commentId => {
  const { deleteComment } = this.props;
  const { comments } = this.state; 
  // 定义处理函数并绑定this
  const handleOk = function() { 
    deleteComment(commentId);
    const targetPosition = _.findIndex(comments, item => item._id === commentId);
    if (targetPosition !== -1) {
      this.setState(prevState => ({
        comments: [
          ...prevState.comments.slice(0, targetPosition),
          ...prevState.comments.slice(targetPosition + 1)
        ]
      }));
    }
  }.bind(this);
  confirm({
    title: 'Are you sure delete this?',
    okText: 'Yes',
    okType: 'danger',
    cancelText: 'No',
    onOk: handleOk
  });
}

这三个方案里,方案一最简洁,也是React组件里最常用的写法,推荐优先使用~

内容的提问来源于stack exchange,提问作者Juan P. Ortiz

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.21 07:34:11