The bags are used for containment and prevention of contamination by air borne spores of other fungi.
Bags are also hang-able so you can grow more mushrooms in a smaller space by stacking the bags on cordage thus having the ability to as much a quadruple the amount of mushrooms per square foot of floor space.
And as Dominik brought up they help keep the mycelium moist
enough to grow and thrive and thus fruit several times once the substrate is fully occupied.
Also by keeping the strain in bags it is easier to use the spent bag to inoculate new bags or logs or chip heaps and thus get even more mushrooms from your initial purchase.
Redhawk