React-Native调用AWS Lambda流式接口EventStream为空报错问题
React-Native调用AWS Lambda流式接口异常处理方案
问题概述
在React-Native中调用AWS Lambda的InvokeWithResponseStream接口时,Lambda正常触发并返回流式响应(CloudWatch可验证),但客户端收到的响应中EventStream为空对象,执行for await...of遍历时抛出TypeError: Object is not async iterable异常,相同代码在React Web环境运行正常。
核心原因
React-Native运行环境与Web存在差异,所使用的3.335.0版本AWS SDK对React-Native的流式响应处理存在适配缺陷,未能正确解析application/vnd.amazon.eventstream格式的响应体,导致EventStream无法被实例化为异步可迭代对象。
解决方案
1. 修正AWS客户端实例使用
代码中导入了LambdaClient但实际误用了旧版的Lambda类,替换为标准的LambdaClient:
import { LambdaClient, InvokeWithResponseStreamCommand } from "@aws-sdk/client-lambda" import "react-native-url-polyfill/auto"; import 'react-native-get-random-values' async streamAWS(payload) { try { const lambdaClient = new LambdaClient({ region: 'us-west-1', credentials: { accessKeyId, secretAccessKey } }); return lambdaClient.send(new InvokeWithResponseStreamCommand({ FunctionName: 'test_stream', Payload: JSON.stringify({ payload }) })); } catch (error) { console.log(error); } }
2. 升级AWS SDK版本
3.335.0版本存在React-Native流式处理的已知bug,升级至3.400.0及以上版本修复适配问题:
npm install @aws-sdk/client-lambda@latest # 或使用yarn yarn add @aws-sdk/client-lambda@latest
3. 手动解析EventStream响应
若升级SDK后仍有问题,可通过polyfill手动解析响应体:
- 安装依赖:
npm install @aws-sdk/eventstream-codec react-native-blob-util
- 修改流处理代码:
import { TextDecoder } from 'text-decoding'; import { decode } from "@aws-sdk/eventstream-codec"; import { readBlob } from 'react-native-blob-util'; useLayoutEffect(() => { async function stream() { const lambdaResponse = await awsService("payload"); // 转换响应为Blob并读取为ArrayBuffer const blob = await lambdaResponse.EventStream.transformToBlob(); const arrayBuffer = await readBlob(blob); const decoder = new TextDecoder("utf-8"); // 手动解码EventStream for (const event of decode(new Uint8Array(arrayBuffer))) { if (event.headers[':event-type'].value === 'PayloadChunk') { const text = decoder.decode(event.payload); setTitle(oldText => oldText + text.replaceAll('"', '')); } } } stream(); }, []);
4. 显式指定HTTP客户端
确保AWS SDK使用React-Native兼容的fetch客户端:
const lambdaClient = new LambdaClient({ region: 'us-west-1', credentials: { ... }, requestHandler: { metadata: { handlerProtocol: "http/1.1" }, fetch: fetch } });
内容的提问来源于stack exchange,提问作者Carlo
相关产品推荐
相关产品推荐

