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

React中setState异步无法即时更新state 后续函数取不到值如何解决?

解决方法

方法一:使用setState的回调参数

setState方法支持传入第二个参数,作为状态更新完成后才会执行的回调函数,你可以把getCustomerName的调用放在这个回调里,就能保证读取到最新的customer状态:

handleChangeCC = customercode => {    
  this.setState({ customercode });    
  var customer1 = customercode.label;
  // 第二个参数为状态更新完成后的回调
  this.setState({ customer: customer1 }, () => {
    console.log(`Option selected1:`, this.state.customer);
    this.getCustomerName();
  });
};

方法二:直接传递变量参数

不需要依赖state存储的值,直接把已经获取到的客户编码传给getCustomerName方法,完全绕过setState异步的问题:
修改handleChangeCC逻辑:

handleChangeCC = customercode => {    
  this.setState({ customercode });    
  var customer1 = customercode.label;
  this.setState({ customer: customer1 });
  console.log(`Option selected1:`, customer1);
  // 直接把变量作为参数传入
  this.getCustomerName(customer1);
};

同步修改getCustomerName接收参数:

// 新增入参code
getCustomerName = (code) => {    
  var Items = [];
  // 优先取传入的参数,没有传入时再读state做兼容
  var requestCode = code || this.state.customer;
  console.log('CustomerCode:' + requestCode);
  axios.post('https://localhost:44303/api/observation/GetCustomerName?&code=' + requestCode).then(response => {
    console.log('Response=' + response.data);
    response.data.map(item => {
      var obj = new Object();
      obj.label = item;
      Items.push(obj);
    });
    // 如果需要读取更新后的customerName,也可以放到setState的回调里
    this.setState({ customerName: Items }, () => {
      console.log('customerName:' + this.state.customerName);
    });
  });
};

如果getCustomerName还有其他不需要传参的调用场景,方法一的兼容性更好;如果仅在当前下拉变更的场景调用,方法二逻辑更直接、性能也更高。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 17:45:05