Changing player controller's input mode multiple times in the same frame doesn't work?

I’m building a menu system with support for nested menus. I have MenuSetup and MenuTearDown functions for each menu that get called as they’re opened/closed. In each function there is code that switches the input mode to FInputModeUIOnly for MenuSetup and FInputModeGameOnly for MenuTearDown.

This system works for first level menus, but when I try opening a nested menu from the first menu, MenuTearDown gets called on the first menu, changing the input to FInputModeGameOnly, and then calls MenuSetup on the second menu, which should change the input back to FInputModeUIOnly. Now what appears on screen is correct, the first menu disappears and the second menu renders properly. But the problem I’m having is the input mode seems to stay in FInputModeGameOnly and doesn’t switch back to FInputModeUIOnly.

void UMenuBase::MenuSetup(UMenuBase* PrevMenu) {
  ...

  FInputModeUIOnly input_mode;
  input_mode.SetWidgetToFocus(this->TakeWidget());
  input_mode.SetLockMouseToViewportBehavior(EMouseLockMode::DoNotLock);
  player_controller->SetInputMode(input_mode);
  player_controller->SetShowMouseCursor(true);
  this->MenuActive = true;
  
  ...
}

void UMenuBase::MenuTearDown(bool OpenPreviousMenu) {
  ...

  FInputModeGameOnly input_mode;
  player_controller->SetInputMode(input_mode);
  player_controller->SetShowMouseCursor(false);
  this->MenuActive = false;

  ...

  if (OpenPreviousMenu) {
    if (this->PreviousMenu) {
      this->PreviousMenu->MenuSetup();
      return;
    }
  }
}