This can happen precisely because the magma is at such depths. Think of CO2 in soda or coke. When the drink is closed and pressurised, the CO2 is dissolved in the liquid. This means it's part of one physical phase. There is one "thing" that contains the liquid and the CO2 together: the CO2 is not a gas! Only when you open the bottle, the CO2 can escape being dissolved in the liquid, and separates from the liquid as a distinct gas phase.
The same thing happens in magmas. While the magmas are pressurised at depths they have water dissolved in them. Note that this water is not separate liquid water or vapour flowing around the magma. It is inside the magma in one physical entity. Think of dissolving salt in water - you can't see salt grains but it's there. Anyway, once the magma rises it loses pressure. This causes the water to separate out from the magma into a distinct vapour phase that rises and expands rapidly, causing the explosive eruption.