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

React-Expo无法处理Azure Functions响应问题求助

问题:Azure Function API连接React应用时await函数挂起,无法处理响应

免责声明:我是JS新手,这个问题可能很容易解决,但我已经查阅了网上相关的所有资源和Stack Overflow帖子

我一直没调试出问题所在,可能只是某个简单的遗漏点:

我想把Azure Function API连接到React应用(用Expo运行),但无法处理响应,导致await函数一直挂起。

Azure Functions API代码

import logging

import azure.functions as func
import json


def main(req: func.HttpRequest) -> func.HttpResponse:
    logging.info('Python HTTP trigger function processed a request.')


    return func.HttpResponse(
        json.dumps({
            'recommendations': [1,2,3,4,5]
            }),
        mimetype="application/json"
        );

React应用代码(Expo)

class App extends Component {
  state = {
    selectedUser: 0,
    step: 0,
    recommendations: 1
  };

  goToStep0 = async () => {
    this.setState({ step: 0, recommendations: 1 });
  };

  goToStep1 = async () => {
    const { data: rec } = await axios.get(config.API_URL);
    //const rec = await axios.get(config.API_URL);
    // const options = {method: "GET"};
    // var rec;

    // fetch(config.API_URL,options)
    // .then(data => {rec = data.recommendations;});

    
    this.setState({ step: 1, recommendations: rec });
  };

Azure函数每次都能接收请求并返回成功响应。

已尝试的方法

  • 修改Azure函数应用使其返回字符串
  • 尝试用fetch发起请求
  • 移除async,使用传统方式发起请求:
    var rec;
    fetch(config.API_URL)
    .then(response => response.json())
    .then(data => {
    rec = data
    });
    
  • 还有至少10种我已经遗忘的尝试(我在这个问题上已经花了4个多小时...)

补充:应用渲染部分代码(法语原文)

render() {
        if (!config.API_URL) {
          return (
            <View style={styles.container}>
              <Image
                style={{ resizeMode: "center", width: 450, height: 150 }}
                source={require("./assets/icon-flat.png")}
              />
              <Text style={{ color: "red", margin: 20 }}>
                L'app n'est pas configurée correctement. Mettez à jour le fichier
                config.json comme indiqué dans le README.
              </Text>
            </View>
          );
        }
        return (
          <View style={styles.container}>
            <Image
              style={{ resizeMode: "center", width: 450, height: 150 }}
              source={require("./assets/icon-flat.png")}
            />
            <Text style={{ fontSize: 18, padding: 20, textAlign: "center" }}>
              Choisissez votre profil afin de recevoir des recommendations de
              lecture personnalisées : {this.state.recommendations.toString()}
              Quel est mon état : {this.state.step}
            </Text>
            <Picker
              style={{ height: 200, width: "80%", margin: 30 }}
              selectedValue={this.state.selectedUser}
              onValueChange={value => this.setState({ selectedUser: value })}
            >
              {[...Array(10000).keys()].map(e => (
                <Picker.Item key={e} label={`User ${e}`} value={e} />
              ))}
            </Picker>
            <Button title="Se connecter" onPress={this.goToStep1} />
          </View>
        );
      }
    }

解决方案

  1. 检查CORS配置:Azure Functions默认限制跨域请求,需在Azure门户的函数应用设置中,添加Expo应用的域名(如本地开发的exp://localhost:19000)到CORS允许列表。测试阶段可暂时允许所有来源*,生产环境需严格配置。

  2. 添加错误捕获并修正数据取值:原goToStep1函数无错误处理,请求出错会静默失败;同时API返回的是包含recommendations字段的对象,需正确取值:

goToStep1 = async () => {
  try {
    const { data } = await axios.get(config.API_URL);
    this.setState({ step: 1, recommendations: data.recommendations });
  } catch (error) {
    console.error('请求出错:', error);
    // 可在此添加用户可见的错误提示
  }
};
  1. 修正fetch用法:fetch是异步操作,需在then链内调用setState,否则无法获取异步返回的数据:
goToStep1 = () => {
  fetch(config.API_URL)
    .then(response => {
      if (!response.ok) throw new Error('请求失败');
      return response.json();
    })
    .then(data => {
      this.setState({ step: 1, recommendations: data.recommendations });
    })
    .catch(error => console.error('请求出错:', error));
};
  1. 验证API地址正确性:确认config.API_URL是Azure函数的有效触发地址,本地运行的函数地址通常为http://localhost:7071/api/<function-name>,线上地址需包含访问密钥(若开启密钥验证)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 01:10:19