如何在Hono.js中使用异步服务器组件?报错解决与实现
Hono.js异步服务器组件实现问题及解决方案
问题代码
用户尝试在Hono.js中编写异步服务器组件,代码如下:
const app = new Hono() const AsyncComponent = async () => { await new Promise((resolve) => setTimeout(resolve, 1000)); return <h1>Hello from async</h1>; } app.get('/', (c) => { const messages = ['Good Morning', 'Good Evening', 'Good Night'] return c.html(<div> <AsyncComponent /> </div>) })
报错信息
TypeScript类型错误
'Promise<HtmlEscapedString>' is not assignable to type string.
运行时错误
TypeError: str.search is not a function
原因分析
Hono的默认c.html()方法要求传入同步生成的HtmlEscapedString或字符串,而异步组件返回的是Promise对象。直接在JSX中使用异步组件会导致Promise被当作普通子元素传递,既不符合类型约束,运行时Hono内部尝试对Promise调用search方法(用于HTML处理)时也会报错。
Next.js的异步服务器组件是框架层面的特殊实现,Hono作为轻量HTTP框架需要使用自身提供的异步渲染API来实现类似功能。
解决方案
方法1:使用htmlAsync异步渲染API
引入Hono的htmlAsync工具,将包含异步组件的JSX转为可等待的HTML字符串,再传入c.html():
import { Hono } from 'hono' import { htmlAsync } from 'hono/html' const app = new Hono() const AsyncComponent = async () => { await new Promise(resolve => setTimeout(resolve, 1000)) return <h1>Hello from async</h1> } app.get('/', async (c) => { const messages = ['Good Morning', 'Good Evening', 'Good Night'] const htmlContent = await htmlAsync(<div> <AsyncComponent /> </div>) return c.html(htmlContent) })
方法2:直接等待异步组件结果
如果异步组件是独立的,可直接等待其返回结果后插入JSX:
app.get('/', async (c) => { const asyncContent = await AsyncComponent() return c.html(<div>{asyncContent}</div>) })
注意事项
- 确保路由处理函数添加
async关键字,以支持异步操作 - 当前使用的Hono 3.7.5版本已支持
htmlAsyncAPI,无需升级 - tsconfig的JSX配置保持现有设置即可:
"jsx": "react-jsx", "jsxFragmentFactory": "Fragment", "jsxImportSource": "hono/jsx"
内容的提问来源于stack exchange,提问作者RuslanGlaznyov
相关产品推荐
相关产品推荐

