Automatic switching is by design: AirPods follow whichever of your devices starts playing audio, and a Mac that was recently used — or one that plays a notification or system sound — can grab the connection even while the iPhone is mid-sentence. Both devices being signed into the same Apple Account is a requirement.
The key control is per device: on the Mac, System Settings → Bluetooth → (i) next to your AirPods → 'Connect to This Mac' offers Automatically / When Last Connected / Never. On the iPhone the same control is under Settings → Bluetooth → (i) → 'Connect to This iPhone'. Setting the Mac to 'When Last Connected' stops it from stealing audio; the iPhone side can stay on Automatically.
Why it still grabs sometimes even then: notifications and call routing behave differently from media playback, and a Mac that wakes from sleep may briefly claim the connection. The most predictable setup is: Mac on 'When Last Connected', switch to it manually via the menu-bar audio control when you want to use it, and keep firmware and macOS current — switching behaviour has been tuned across firmware generations.
— Osnivo Editorial