非异步请求调用方法报错:单步调试正常但前端仍报错的解决
解决Spring MVC异步模式调用错误:"It is illegal to call this method if the current request is not in asynchronous mode"
错误信息
{ "status" : 1, "code" : 0, "message" : "It is illegal to call this method if the current request is not in asynchronous mode (i.e. isAsyncStarted() returns false)", "param" : null, "data" : null }
问题场景
单步调试所有业务代码均正常执行,日志能完整输出请求和响应参数,但前端始终收到上述错误响应。相关代码如下:
Controller代码
@RestController @RequestMapping(value = "/cashier/v1") public class PayController { @ApiOperation("pay for shop") @GetMapping(value = "/pay") public ResponseVO<PayResponseVO> pay(ShopPayRequestVO requestVO, HttpServletRequest request) { return payService.pay(requestVO, request); } }
Service实现
@Service @Slf4j public class PayServiceImpl implements IPayService { @Override public ResponseVO<PayResponseVO> pay(ShopPayRequestVO requestVO, HttpServletRequest request) throws AuthorizationException { log.info("pay request param:{}", JSON.toJSONString(requestVO)); PayResponseVO vo = new PayResponseVO(); // 业务逻辑省略 vo.setOrderNo(businessOrderNo); vo.setShopId(requestVO.getShopId()); log.info("pay response param:{}", JSON.toJSONString(vo)); return ResponseVO.success(vo); } }
响应VO
@Data public class PayResponseVO { private Object payInfo; private String orderNo; private String shopId; }
解决方法
排查后发现问题出在响应VO的payInfo字段:该字段实际被赋值了一个与请求上下文绑定的异步相关对象(例如AsyncContext实例),在JSON序列化过程中,框架尝试访问该对象的异步方法,但当前请求并未开启异步模式,因此触发错误。
两种可行解决方式:
- 转换数据类型:避免直接返回与请求上下文绑定的异步对象,将
payInfo字段转换为纯数据DTO,只保留业务所需的字段信息。 - 开启请求异步模式:如果业务确实需要异步处理,修改Controller方法为异步形式:
同时确保Spring配置中已开启异步支持(默认通常已开启,若未配置可在配置类添加@GetMapping(value = "/pay") public Callable<ResponseVO<PayResponseVO>> pay(ShopPayRequestVO requestVO, HttpServletRequest request) { return () -> payService.pay(requestVO, request); }@EnableAsync注解)。
内容的提问来源于stack exchange,提问作者Andy Wong
相关产品推荐
相关产品推荐

