Phoenix LiveView中on_mount赋值current_user后模态框保存时丢失问题
问题分析与解决方案
核心原因
你遇到的current_user找不到的KeyError,本质是LiveComponent没有从父LiveView接收到current_user这个assign。虽然根LiveView通过on_mount注入了current_user,但LiveComponent不会自动继承父组件的所有assigns,必须显式传递。
具体修复步骤
传递
current_user到FormComponent
在渲染编辑用的FormComponent时(比如在WeightLive.Show或父组件的模板里),添加current_user: @current_user参数:<%= live_component @socket, HealthTrackerWeb.WeightLive.FormComponent, id: @weight.id, action: @live_action, weight: @weight, current_user: @current_user %>确保组件接收并使用该assign
在FormComponent的update/2或mount/3函数中,确认current_user被存入组件的assigns:def update(assigns, socket) do {:ok, assign(socket, assigns)} end然后在
handle_event("save", _, socket)里,通过socket.assigns.current_user访问即可,不会再触发KeyError。额外检查:确认on_mount覆盖所有需要的LiveView
如果编辑功能对应独立的LiveView(而非组件),要确保该LiveView的路由或模块定义中,同样添加了on_mount HealthTrackerWeb.UserLiveAuth,保证current_user被注入。
验证要点
- 触发save事件前,在组件模板中添加
<%= inspect @current_user %>,确认该值存在; - 检查日志中组件的assigns输出,确认
current_user已被传递。
内容的提问来源于stack exchange,提问作者martins
相关产品推荐
相关产品推荐

